]> git.saurik.com Git - redis.git/blob - src/t_set.c
138a2f8de28888d7c853be841f5b83221701a8db
[redis.git] / src / t_set.c
1 #include "redis.h"
2
3 /*-----------------------------------------------------------------------------
4 * Set Commands
5 *----------------------------------------------------------------------------*/
6
7 /* Factory method to return a set that *can* hold "value". When the object has
8 * an integer-encodable value, an intset will be returned. Otherwise a regular
9 * hash table. */
10 robj *setTypeCreate(robj *value) {
11 if (isObjectRepresentableAsLongLong(value,NULL) == REDIS_OK)
12 return createIntsetObject();
13 return createSetObject();
14 }
15
16 int setTypeAdd(robj *subject, robj *value) {
17 long long llval;
18 if (subject->encoding == REDIS_ENCODING_HT) {
19 if (dictAdd(subject->ptr,value,NULL) == DICT_OK) {
20 incrRefCount(value);
21 return 1;
22 }
23 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
24 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
25 uint8_t success = 0;
26 subject->ptr = intsetAdd(subject->ptr,llval,&success);
27 if (success) {
28 /* Convert to regular set when the intset contains
29 * too many entries. */
30 if (intsetLen(subject->ptr) > server.set_max_intset_entries)
31 setTypeConvert(subject,REDIS_ENCODING_HT);
32 return 1;
33 }
34 } else {
35 /* Failed to get integer from object, convert to regular set. */
36 setTypeConvert(subject,REDIS_ENCODING_HT);
37
38 /* The set *was* an intset and this value is not integer
39 * encodable, so dictAdd should always work. */
40 redisAssert(dictAdd(subject->ptr,value,NULL) == DICT_OK);
41 incrRefCount(value);
42 return 1;
43 }
44 } else {
45 redisPanic("Unknown set encoding");
46 }
47 return 0;
48 }
49
50 int setTypeRemove(robj *setobj, robj *value) {
51 long long llval;
52 if (setobj->encoding == REDIS_ENCODING_HT) {
53 if (dictDelete(setobj->ptr,value) == DICT_OK) {
54 if (htNeedsResize(setobj->ptr)) dictResize(setobj->ptr);
55 return 1;
56 }
57 } else if (setobj->encoding == REDIS_ENCODING_INTSET) {
58 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
59 int success;
60 setobj->ptr = intsetRemove(setobj->ptr,llval,&success);
61 if (success) return 1;
62 }
63 } else {
64 redisPanic("Unknown set encoding");
65 }
66 return 0;
67 }
68
69 int setTypeIsMember(robj *subject, robj *value) {
70 long long llval;
71 if (subject->encoding == REDIS_ENCODING_HT) {
72 return dictFind((dict*)subject->ptr,value) != NULL;
73 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
74 if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
75 return intsetFind((intset*)subject->ptr,llval);
76 }
77 } else {
78 redisPanic("Unknown set encoding");
79 }
80 return 0;
81 }
82
83 setTypeIterator *setTypeInitIterator(robj *subject) {
84 setTypeIterator *si = zmalloc(sizeof(setTypeIterator));
85 si->subject = subject;
86 si->encoding = subject->encoding;
87 if (si->encoding == REDIS_ENCODING_HT) {
88 si->di = dictGetIterator(subject->ptr);
89 } else if (si->encoding == REDIS_ENCODING_INTSET) {
90 si->ii = 0;
91 } else {
92 redisPanic("Unknown set encoding");
93 }
94 return si;
95 }
96
97 void setTypeReleaseIterator(setTypeIterator *si) {
98 if (si->encoding == REDIS_ENCODING_HT)
99 dictReleaseIterator(si->di);
100 zfree(si);
101 }
102
103 /* Move to the next entry in the set. Returns the object at the current
104 * position.
105 *
106 * Since set elements can be internally be stored as redis objects or
107 * simple arrays of integers, setTypeNext returns the encoding of the
108 * set object you are iterating, and will populate the appropriate pointer
109 * (eobj) or (llobj) accordingly.
110 *
111 * When there are no longer elements -1 is returned.
112 * Returned objects ref count is not incremented, so this function is
113 * copy on write friendly. */
114 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele) {
115 if (si->encoding == REDIS_ENCODING_HT) {
116 dictEntry *de = dictNext(si->di);
117 if (de == NULL) return -1;
118 *objele = dictGetEntryKey(de);
119 } else if (si->encoding == REDIS_ENCODING_INTSET) {
120 if (!intsetGet(si->subject->ptr,si->ii++,llele))
121 return -1;
122 }
123 return si->encoding;
124 }
125
126 /* The not copy on write friendly version but easy to use version
127 * of setTypeNext() is setTypeNextObject(), returning new objects
128 * or incrementing the ref count of returned objects. So if you don't
129 * retain a pointer to this object you should call decrRefCount() against it.
130 *
131 * This function is the way to go for write operations where COW is not
132 * an issue as the result will be anyway of incrementing the ref count. */
133 robj *setTypeNextObject(setTypeIterator *si) {
134 int64_t intele;
135 robj *objele;
136 int encoding;
137
138 encoding = setTypeNext(si,&objele,&intele);
139 switch(encoding) {
140 case -1: return NULL;
141 case REDIS_ENCODING_INTSET:
142 return createStringObjectFromLongLong(intele);
143 case REDIS_ENCODING_HT:
144 incrRefCount(objele);
145 return objele;
146 default:
147 redisPanic("Unsupported encoding");
148 }
149 return NULL; /* just to suppress warnings */
150 }
151
152 /* Return random element from a non empty set.
153 * The returned element can be a int64_t value if the set is encoded
154 * as an "intset" blob of integers, or a redis object if the set
155 * is a regular set.
156 *
157 * The caller provides both pointers to be populated with the right
158 * object. The return value of the function is the object->encoding
159 * field of the object and is used by the caller to check if the
160 * int64_t pointer or the redis object pointere was populated.
161 *
162 * When an object is returned (the set was a real set) the ref count
163 * of the object is not incremented so this function can be considered
164 * copy on write friendly. */
165 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele) {
166 if (setobj->encoding == REDIS_ENCODING_HT) {
167 dictEntry *de = dictGetRandomKey(setobj->ptr);
168 *objele = dictGetEntryKey(de);
169 } else if (setobj->encoding == REDIS_ENCODING_INTSET) {
170 *llele = intsetRandom(setobj->ptr);
171 } else {
172 redisPanic("Unknown set encoding");
173 }
174 return setobj->encoding;
175 }
176
177 unsigned long setTypeSize(robj *subject) {
178 if (subject->encoding == REDIS_ENCODING_HT) {
179 return dictSize((dict*)subject->ptr);
180 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
181 return intsetLen((intset*)subject->ptr);
182 } else {
183 redisPanic("Unknown set encoding");
184 }
185 }
186
187 /* Convert the set to specified encoding. The resulting dict (when converting
188 * to a hashtable) is presized to hold the number of elements in the original
189 * set. */
190 void setTypeConvert(robj *setobj, int enc) {
191 setTypeIterator *si;
192 redisAssert(setobj->type == REDIS_SET &&
193 setobj->encoding == REDIS_ENCODING_INTSET);
194
195 if (enc == REDIS_ENCODING_HT) {
196 int64_t intele;
197 dict *d = dictCreate(&setDictType,NULL);
198 robj *element;
199
200 /* Presize the dict to avoid rehashing */
201 dictExpand(d,intsetLen(setobj->ptr));
202
203 /* To add the elements we extract integers and create redis objects */
204 si = setTypeInitIterator(setobj);
205 while (setTypeNext(si,NULL,&intele) != -1) {
206 element = createStringObjectFromLongLong(intele);
207 redisAssert(dictAdd(d,element,NULL) == DICT_OK);
208 }
209 setTypeReleaseIterator(si);
210
211 setobj->encoding = REDIS_ENCODING_HT;
212 zfree(setobj->ptr);
213 setobj->ptr = d;
214 } else {
215 redisPanic("Unsupported set conversion");
216 }
217 }
218
219 void saddCommand(redisClient *c) {
220 robj *set;
221 int j, added = 0;
222
223 set = lookupKeyWrite(c->db,c->argv[1]);
224 if (set == NULL) {
225 set = setTypeCreate(c->argv[2]);
226 dbAdd(c->db,c->argv[1],set);
227 } else {
228 if (set->type != REDIS_SET) {
229 addReply(c,shared.wrongtypeerr);
230 return;
231 }
232 }
233
234 for (j = 2; j < c->argc; j++) {
235 c->argv[j] = tryObjectEncoding(c->argv[j]);
236 if (setTypeAdd(set,c->argv[j])) added++;
237 }
238 if (added) signalModifiedKey(c->db,c->argv[1]);
239 server.dirty += added;
240 addReplyLongLong(c,added);
241 }
242
243 void sremCommand(redisClient *c) {
244 robj *set;
245
246 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
247 checkType(c,set,REDIS_SET)) return;
248
249 c->argv[2] = tryObjectEncoding(c->argv[2]);
250 if (setTypeRemove(set,c->argv[2])) {
251 if (setTypeSize(set) == 0) dbDelete(c->db,c->argv[1]);
252 signalModifiedKey(c->db,c->argv[1]);
253 server.dirty++;
254 addReply(c,shared.cone);
255 } else {
256 addReply(c,shared.czero);
257 }
258 }
259
260 void smoveCommand(redisClient *c) {
261 robj *srcset, *dstset, *ele;
262 srcset = lookupKeyWrite(c->db,c->argv[1]);
263 dstset = lookupKeyWrite(c->db,c->argv[2]);
264 ele = c->argv[3] = tryObjectEncoding(c->argv[3]);
265
266 /* If the source key does not exist return 0 */
267 if (srcset == NULL) {
268 addReply(c,shared.czero);
269 return;
270 }
271
272 /* If the source key has the wrong type, or the destination key
273 * is set and has the wrong type, return with an error. */
274 if (checkType(c,srcset,REDIS_SET) ||
275 (dstset && checkType(c,dstset,REDIS_SET))) return;
276
277 /* If srcset and dstset are equal, SMOVE is a no-op */
278 if (srcset == dstset) {
279 addReply(c,shared.cone);
280 return;
281 }
282
283 /* If the element cannot be removed from the src set, return 0. */
284 if (!setTypeRemove(srcset,ele)) {
285 addReply(c,shared.czero);
286 return;
287 }
288
289 /* Remove the src set from the database when empty */
290 if (setTypeSize(srcset) == 0) dbDelete(c->db,c->argv[1]);
291 signalModifiedKey(c->db,c->argv[1]);
292 signalModifiedKey(c->db,c->argv[2]);
293 server.dirty++;
294
295 /* Create the destination set when it doesn't exist */
296 if (!dstset) {
297 dstset = setTypeCreate(ele);
298 dbAdd(c->db,c->argv[2],dstset);
299 }
300
301 /* An extra key has changed when ele was successfully added to dstset */
302 if (setTypeAdd(dstset,ele)) server.dirty++;
303 addReply(c,shared.cone);
304 }
305
306 void sismemberCommand(redisClient *c) {
307 robj *set;
308
309 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
310 checkType(c,set,REDIS_SET)) return;
311
312 c->argv[2] = tryObjectEncoding(c->argv[2]);
313 if (setTypeIsMember(set,c->argv[2]))
314 addReply(c,shared.cone);
315 else
316 addReply(c,shared.czero);
317 }
318
319 void scardCommand(redisClient *c) {
320 robj *o;
321
322 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
323 checkType(c,o,REDIS_SET)) return;
324
325 addReplyLongLong(c,setTypeSize(o));
326 }
327
328 void spopCommand(redisClient *c) {
329 robj *set, *ele;
330 int64_t llele;
331 int encoding;
332
333 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
334 checkType(c,set,REDIS_SET)) return;
335
336 encoding = setTypeRandomElement(set,&ele,&llele);
337 if (encoding == REDIS_ENCODING_INTSET) {
338 ele = createStringObjectFromLongLong(llele);
339 set->ptr = intsetRemove(set->ptr,llele,NULL);
340 } else {
341 incrRefCount(ele);
342 setTypeRemove(set,ele);
343 }
344
345 /* Change argv to replicate as SREM */
346 c->argc = 3;
347 c->argv = zrealloc(c->argv,sizeof(robj*)*(c->argc));
348
349 /* Overwrite SREM with SPOP (same length) */
350 redisAssert(sdslen(c->argv[0]->ptr) == 4);
351 memcpy(c->argv[0]->ptr, "SREM", 4);
352
353 /* Popped element already has incremented refcount */
354 c->argv[2] = ele;
355
356 addReplyBulk(c,ele);
357 if (setTypeSize(set) == 0) dbDelete(c->db,c->argv[1]);
358 signalModifiedKey(c->db,c->argv[1]);
359 server.dirty++;
360 }
361
362 void srandmemberCommand(redisClient *c) {
363 robj *set, *ele;
364 int64_t llele;
365 int encoding;
366
367 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
368 checkType(c,set,REDIS_SET)) return;
369
370 encoding = setTypeRandomElement(set,&ele,&llele);
371 if (encoding == REDIS_ENCODING_INTSET) {
372 addReplyBulkLongLong(c,llele);
373 } else {
374 addReplyBulk(c,ele);
375 }
376 }
377
378 int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
379 return setTypeSize(*(robj**)s1)-setTypeSize(*(robj**)s2);
380 }
381
382 void sinterGenericCommand(redisClient *c, robj **setkeys, unsigned long setnum, robj *dstkey) {
383 robj **sets = zmalloc(sizeof(robj*)*setnum);
384 setTypeIterator *si;
385 robj *eleobj, *dstset = NULL;
386 int64_t intobj;
387 void *replylen = NULL;
388 unsigned long j, cardinality = 0;
389 int encoding;
390
391 for (j = 0; j < setnum; j++) {
392 robj *setobj = dstkey ?
393 lookupKeyWrite(c->db,setkeys[j]) :
394 lookupKeyRead(c->db,setkeys[j]);
395 if (!setobj) {
396 zfree(sets);
397 if (dstkey) {
398 if (dbDelete(c->db,dstkey)) {
399 signalModifiedKey(c->db,dstkey);
400 server.dirty++;
401 }
402 addReply(c,shared.czero);
403 } else {
404 addReply(c,shared.emptymultibulk);
405 }
406 return;
407 }
408 if (checkType(c,setobj,REDIS_SET)) {
409 zfree(sets);
410 return;
411 }
412 sets[j] = setobj;
413 }
414 /* Sort sets from the smallest to largest, this will improve our
415 * algorithm's performace */
416 qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality);
417
418 /* The first thing we should output is the total number of elements...
419 * since this is a multi-bulk write, but at this stage we don't know
420 * the intersection set size, so we use a trick, append an empty object
421 * to the output list and save the pointer to later modify it with the
422 * right length */
423 if (!dstkey) {
424 replylen = addDeferredMultiBulkLength(c);
425 } else {
426 /* If we have a target key where to store the resulting set
427 * create this key with an empty set inside */
428 dstset = createIntsetObject();
429 }
430
431 /* Iterate all the elements of the first (smallest) set, and test
432 * the element against all the other sets, if at least one set does
433 * not include the element it is discarded */
434 si = setTypeInitIterator(sets[0]);
435 while((encoding = setTypeNext(si,&eleobj,&intobj)) != -1) {
436 for (j = 1; j < setnum; j++) {
437 if (encoding == REDIS_ENCODING_INTSET) {
438 /* intset with intset is simple... and fast */
439 if (sets[j]->encoding == REDIS_ENCODING_INTSET &&
440 !intsetFind((intset*)sets[j]->ptr,intobj))
441 {
442 break;
443 /* in order to compare an integer with an object we
444 * have to use the generic function, creating an object
445 * for this */
446 } else if (sets[j]->encoding == REDIS_ENCODING_HT) {
447 eleobj = createStringObjectFromLongLong(intobj);
448 if (!setTypeIsMember(sets[j],eleobj)) {
449 decrRefCount(eleobj);
450 break;
451 }
452 decrRefCount(eleobj);
453 }
454 } else if (encoding == REDIS_ENCODING_HT) {
455 /* Optimization... if the source object is integer
456 * encoded AND the target set is an intset, we can get
457 * a much faster path. */
458 if (eleobj->encoding == REDIS_ENCODING_INT &&
459 sets[j]->encoding == REDIS_ENCODING_INTSET &&
460 !intsetFind((intset*)sets[j]->ptr,(long)eleobj->ptr))
461 {
462 break;
463 /* else... object to object check is easy as we use the
464 * type agnostic API here. */
465 } else if (!setTypeIsMember(sets[j],eleobj)) {
466 break;
467 }
468 }
469 }
470
471 /* Only take action when all sets contain the member */
472 if (j == setnum) {
473 if (!dstkey) {
474 if (encoding == REDIS_ENCODING_HT)
475 addReplyBulk(c,eleobj);
476 else
477 addReplyBulkLongLong(c,intobj);
478 cardinality++;
479 } else {
480 if (encoding == REDIS_ENCODING_INTSET) {
481 eleobj = createStringObjectFromLongLong(intobj);
482 setTypeAdd(dstset,eleobj);
483 decrRefCount(eleobj);
484 } else {
485 setTypeAdd(dstset,eleobj);
486 }
487 }
488 }
489 }
490 setTypeReleaseIterator(si);
491
492 if (dstkey) {
493 /* Store the resulting set into the target, if the intersection
494 * is not an empty set. */
495 dbDelete(c->db,dstkey);
496 if (setTypeSize(dstset) > 0) {
497 dbAdd(c->db,dstkey,dstset);
498 addReplyLongLong(c,setTypeSize(dstset));
499 } else {
500 decrRefCount(dstset);
501 addReply(c,shared.czero);
502 }
503 signalModifiedKey(c->db,dstkey);
504 server.dirty++;
505 } else {
506 setDeferredMultiBulkLength(c,replylen,cardinality);
507 }
508 zfree(sets);
509 }
510
511 void sinterCommand(redisClient *c) {
512 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
513 }
514
515 void sinterstoreCommand(redisClient *c) {
516 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
517 }
518
519 #define REDIS_OP_UNION 0
520 #define REDIS_OP_DIFF 1
521 #define REDIS_OP_INTER 2
522
523 void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op) {
524 robj **sets = zmalloc(sizeof(robj*)*setnum);
525 setTypeIterator *si;
526 robj *ele, *dstset = NULL;
527 int j, cardinality = 0;
528
529 for (j = 0; j < setnum; j++) {
530 robj *setobj = dstkey ?
531 lookupKeyWrite(c->db,setkeys[j]) :
532 lookupKeyRead(c->db,setkeys[j]);
533 if (!setobj) {
534 sets[j] = NULL;
535 continue;
536 }
537 if (checkType(c,setobj,REDIS_SET)) {
538 zfree(sets);
539 return;
540 }
541 sets[j] = setobj;
542 }
543
544 /* We need a temp set object to store our union. If the dstkey
545 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
546 * this set object will be the resulting object to set into the target key*/
547 dstset = createIntsetObject();
548
549 /* Iterate all the elements of all the sets, add every element a single
550 * time to the result set */
551 for (j = 0; j < setnum; j++) {
552 if (op == REDIS_OP_DIFF && j == 0 && !sets[j]) break; /* result set is empty */
553 if (!sets[j]) continue; /* non existing keys are like empty sets */
554
555 si = setTypeInitIterator(sets[j]);
556 while((ele = setTypeNextObject(si)) != NULL) {
557 if (op == REDIS_OP_UNION || j == 0) {
558 if (setTypeAdd(dstset,ele)) {
559 cardinality++;
560 }
561 } else if (op == REDIS_OP_DIFF) {
562 if (setTypeRemove(dstset,ele)) {
563 cardinality--;
564 }
565 }
566 decrRefCount(ele);
567 }
568 setTypeReleaseIterator(si);
569
570 /* Exit when result set is empty. */
571 if (op == REDIS_OP_DIFF && cardinality == 0) break;
572 }
573
574 /* Output the content of the resulting set, if not in STORE mode */
575 if (!dstkey) {
576 addReplyMultiBulkLen(c,cardinality);
577 si = setTypeInitIterator(dstset);
578 while((ele = setTypeNextObject(si)) != NULL) {
579 addReplyBulk(c,ele);
580 decrRefCount(ele);
581 }
582 setTypeReleaseIterator(si);
583 decrRefCount(dstset);
584 } else {
585 /* If we have a target key where to store the resulting set
586 * create this key with the result set inside */
587 dbDelete(c->db,dstkey);
588 if (setTypeSize(dstset) > 0) {
589 dbAdd(c->db,dstkey,dstset);
590 addReplyLongLong(c,setTypeSize(dstset));
591 } else {
592 decrRefCount(dstset);
593 addReply(c,shared.czero);
594 }
595 signalModifiedKey(c->db,dstkey);
596 server.dirty++;
597 }
598 zfree(sets);
599 }
600
601 void sunionCommand(redisClient *c) {
602 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
603 }
604
605 void sunionstoreCommand(redisClient *c) {
606 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
607 }
608
609 void sdiffCommand(redisClient *c) {
610 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
611 }
612
613 void sdiffstoreCommand(redisClient *c) {
614 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
615 }