xref: /redis-3.2.3/src/t_set.c (revision 40f822da)
1 /*
2  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *   * Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *   * Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  *   * Neither the name of Redis nor the names of its contributors may be used
14  *     to endorse or promote products derived from this software without
15  *     specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "redis.h"
31 
32 /*-----------------------------------------------------------------------------
33  * Set Commands
34  *----------------------------------------------------------------------------*/
35 
36 void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op);
37 
38 /* Factory method to return a set that *can* hold "value". When the object has
39  * an integer-encodable value, an intset will be returned. Otherwise a regular
40  * hash table. */
41 robj *setTypeCreate(robj *value) {
42     if (isObjectRepresentableAsLongLong(value,NULL) == REDIS_OK)
43         return createIntsetObject();
44     return createSetObject();
45 }
46 
47 int setTypeAdd(robj *subject, robj *value) {
48     long long llval;
49     if (subject->encoding == REDIS_ENCODING_HT) {
50         if (dictAdd(subject->ptr,value,NULL) == DICT_OK) {
51             incrRefCount(value);
52             return 1;
53         }
54     } else if (subject->encoding == REDIS_ENCODING_INTSET) {
55         if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
56             uint8_t success = 0;
57             subject->ptr = intsetAdd(subject->ptr,llval,&success);
58             if (success) {
59                 /* Convert to regular set when the intset contains
60                  * too many entries. */
61                 if (intsetLen(subject->ptr) > server.set_max_intset_entries)
62                     setTypeConvert(subject,REDIS_ENCODING_HT);
63                 return 1;
64             }
65         } else {
66             /* Failed to get integer from object, convert to regular set. */
67             setTypeConvert(subject,REDIS_ENCODING_HT);
68 
69             /* The set *was* an intset and this value is not integer
70              * encodable, so dictAdd should always work. */
71             redisAssertWithInfo(NULL,value,dictAdd(subject->ptr,value,NULL) == DICT_OK);
72             incrRefCount(value);
73             return 1;
74         }
75     } else {
76         redisPanic("Unknown set encoding");
77     }
78     return 0;
79 }
80 
81 int setTypeRemove(robj *setobj, robj *value) {
82     long long llval;
83     if (setobj->encoding == REDIS_ENCODING_HT) {
84         if (dictDelete(setobj->ptr,value) == DICT_OK) {
85             if (htNeedsResize(setobj->ptr)) dictResize(setobj->ptr);
86             return 1;
87         }
88     } else if (setobj->encoding == REDIS_ENCODING_INTSET) {
89         if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
90             int success;
91             setobj->ptr = intsetRemove(setobj->ptr,llval,&success);
92             if (success) return 1;
93         }
94     } else {
95         redisPanic("Unknown set encoding");
96     }
97     return 0;
98 }
99 
100 int setTypeIsMember(robj *subject, robj *value) {
101     long long llval;
102     if (subject->encoding == REDIS_ENCODING_HT) {
103         return dictFind((dict*)subject->ptr,value) != NULL;
104     } else if (subject->encoding == REDIS_ENCODING_INTSET) {
105         if (isObjectRepresentableAsLongLong(value,&llval) == REDIS_OK) {
106             return intsetFind((intset*)subject->ptr,llval);
107         }
108     } else {
109         redisPanic("Unknown set encoding");
110     }
111     return 0;
112 }
113 
114 setTypeIterator *setTypeInitIterator(robj *subject) {
115     setTypeIterator *si = zmalloc(sizeof(setTypeIterator));
116     si->subject = subject;
117     si->encoding = subject->encoding;
118     if (si->encoding == REDIS_ENCODING_HT) {
119         si->di = dictGetIterator(subject->ptr);
120     } else if (si->encoding == REDIS_ENCODING_INTSET) {
121         si->ii = 0;
122     } else {
123         redisPanic("Unknown set encoding");
124     }
125     return si;
126 }
127 
128 void setTypeReleaseIterator(setTypeIterator *si) {
129     if (si->encoding == REDIS_ENCODING_HT)
130         dictReleaseIterator(si->di);
131     zfree(si);
132 }
133 
134 /* Move to the next entry in the set. Returns the object at the current
135  * position.
136  *
137  * Since set elements can be internally be stored as redis objects or
138  * simple arrays of integers, setTypeNext returns the encoding of the
139  * set object you are iterating, and will populate the appropriate pointer
140  * (eobj) or (llobj) accordingly.
141  *
142  * When there are no longer elements -1 is returned.
143  * Returned objects ref count is not incremented, so this function is
144  * copy on write friendly. */
145 int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele) {
146     if (si->encoding == REDIS_ENCODING_HT) {
147         dictEntry *de = dictNext(si->di);
148         if (de == NULL) return -1;
149         *objele = dictGetKey(de);
150     } else if (si->encoding == REDIS_ENCODING_INTSET) {
151         if (!intsetGet(si->subject->ptr,si->ii++,llele))
152             return -1;
153     }
154     return si->encoding;
155 }
156 
157 /* The not copy on write friendly version but easy to use version
158  * of setTypeNext() is setTypeNextObject(), returning new objects
159  * or incrementing the ref count of returned objects. So if you don't
160  * retain a pointer to this object you should call decrRefCount() against it.
161  *
162  * This function is the way to go for write operations where COW is not
163  * an issue as the result will be anyway of incrementing the ref count. */
164 robj *setTypeNextObject(setTypeIterator *si) {
165     int64_t intele;
166     robj *objele;
167     int encoding;
168 
169     encoding = setTypeNext(si,&objele,&intele);
170     switch(encoding) {
171         case -1:    return NULL;
172         case REDIS_ENCODING_INTSET:
173             return createStringObjectFromLongLong(intele);
174         case REDIS_ENCODING_HT:
175             incrRefCount(objele);
176             return objele;
177         default:
178             redisPanic("Unsupported encoding");
179     }
180     return NULL; /* just to suppress warnings */
181 }
182 
183 /* Return random element from a non empty set.
184  * The returned element can be a int64_t value if the set is encoded
185  * as an "intset" blob of integers, or a redis object if the set
186  * is a regular set.
187  *
188  * The caller provides both pointers to be populated with the right
189  * object. The return value of the function is the object->encoding
190  * field of the object and is used by the caller to check if the
191  * int64_t pointer or the redis object pointer was populated.
192  *
193  * When an object is returned (the set was a real set) the ref count
194  * of the object is not incremented so this function can be considered
195  * copy on write friendly. */
196 int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele) {
197     if (setobj->encoding == REDIS_ENCODING_HT) {
198         dictEntry *de = dictGetRandomKey(setobj->ptr);
199         *objele = dictGetKey(de);
200     } else if (setobj->encoding == REDIS_ENCODING_INTSET) {
201         *llele = intsetRandom(setobj->ptr);
202     } else {
203         redisPanic("Unknown set encoding");
204     }
205     return setobj->encoding;
206 }
207 
208 unsigned long setTypeSize(robj *subject) {
209     if (subject->encoding == REDIS_ENCODING_HT) {
210         return dictSize((dict*)subject->ptr);
211     } else if (subject->encoding == REDIS_ENCODING_INTSET) {
212         return intsetLen((intset*)subject->ptr);
213     } else {
214         redisPanic("Unknown set encoding");
215     }
216 }
217 
218 /* Convert the set to specified encoding. The resulting dict (when converting
219  * to a hash table) is presized to hold the number of elements in the original
220  * set. */
221 void setTypeConvert(robj *setobj, int enc) {
222     setTypeIterator *si;
223     redisAssertWithInfo(NULL,setobj,setobj->type == REDIS_SET &&
224                              setobj->encoding == REDIS_ENCODING_INTSET);
225 
226     if (enc == REDIS_ENCODING_HT) {
227         int64_t intele;
228         dict *d = dictCreate(&setDictType,NULL);
229         robj *element;
230 
231         /* Presize the dict to avoid rehashing */
232         dictExpand(d,intsetLen(setobj->ptr));
233 
234         /* To add the elements we extract integers and create redis objects */
235         si = setTypeInitIterator(setobj);
236         while (setTypeNext(si,NULL,&intele) != -1) {
237             element = createStringObjectFromLongLong(intele);
238             redisAssertWithInfo(NULL,element,dictAdd(d,element,NULL) == DICT_OK);
239         }
240         setTypeReleaseIterator(si);
241 
242         setobj->encoding = REDIS_ENCODING_HT;
243         zfree(setobj->ptr);
244         setobj->ptr = d;
245     } else {
246         redisPanic("Unsupported set conversion");
247     }
248 }
249 
250 void saddCommand(redisClient *c) {
251     robj *set;
252     int j, added = 0;
253 
254     set = lookupKeyWrite(c->db,c->argv[1]);
255     if (set == NULL) {
256         set = setTypeCreate(c->argv[2]);
257         dbAdd(c->db,c->argv[1],set);
258     } else {
259         if (set->type != REDIS_SET) {
260             addReply(c,shared.wrongtypeerr);
261             return;
262         }
263     }
264 
265     for (j = 2; j < c->argc; j++) {
266         c->argv[j] = tryObjectEncoding(c->argv[j]);
267         if (setTypeAdd(set,c->argv[j])) added++;
268     }
269     if (added) {
270         signalModifiedKey(c->db,c->argv[1]);
271         notifyKeyspaceEvent("sadd",c->argv[1],c->db->id);
272     }
273     server.dirty += added;
274     addReplyLongLong(c,added);
275 }
276 
277 void sremCommand(redisClient *c) {
278     robj *set;
279     int j, deleted = 0, keyremoved = 0;
280 
281     if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
282         checkType(c,set,REDIS_SET)) return;
283 
284     for (j = 2; j < c->argc; j++) {
285         if (setTypeRemove(set,c->argv[j])) {
286             deleted++;
287             if (setTypeSize(set) == 0) {
288                 dbDelete(c->db,c->argv[1]);
289                 keyremoved = 1;
290                 break;
291             }
292         }
293     }
294     if (deleted) {
295         signalModifiedKey(c->db,c->argv[1]);
296         notifyKeyspaceEvent("srem",c->argv[1],c->db->id);
297         if (keyremoved) notifyKeyspaceEvent("del",c->argv[1],c->db->id);
298         server.dirty += deleted;
299     }
300     addReplyLongLong(c,deleted);
301 }
302 
303 void smoveCommand(redisClient *c) {
304     robj *srcset, *dstset, *ele;
305     srcset = lookupKeyWrite(c->db,c->argv[1]);
306     dstset = lookupKeyWrite(c->db,c->argv[2]);
307     ele = c->argv[3] = tryObjectEncoding(c->argv[3]);
308 
309     /* If the source key does not exist return 0 */
310     if (srcset == NULL) {
311         addReply(c,shared.czero);
312         return;
313     }
314 
315     /* If the source key has the wrong type, or the destination key
316      * is set and has the wrong type, return with an error. */
317     if (checkType(c,srcset,REDIS_SET) ||
318         (dstset && checkType(c,dstset,REDIS_SET))) return;
319 
320     /* If srcset and dstset are equal, SMOVE is a no-op */
321     if (srcset == dstset) {
322         addReply(c,shared.cone);
323         return;
324     }
325 
326     /* If the element cannot be removed from the src set, return 0. */
327     if (!setTypeRemove(srcset,ele)) {
328         addReply(c,shared.czero);
329         return;
330     }
331     notifyKeyspaceEvent("srem",c->argv[1],c->db->id);
332 
333     /* Remove the src set from the database when empty */
334     if (setTypeSize(srcset) == 0) {
335         dbDelete(c->db,c->argv[1]);
336         notifyKeyspaceEvent("del",c->argv[1],c->db->id);
337     }
338     signalModifiedKey(c->db,c->argv[1]);
339     signalModifiedKey(c->db,c->argv[2]);
340     server.dirty++;
341 
342     /* Create the destination set when it doesn't exist */
343     if (!dstset) {
344         dstset = setTypeCreate(ele);
345         dbAdd(c->db,c->argv[2],dstset);
346     }
347 
348     /* An extra key has changed when ele was successfully added to dstset */
349     if (setTypeAdd(dstset,ele)) {
350         server.dirty++;
351         notifyKeyspaceEvent("sadd",c->argv[2],c->db->id);
352     }
353     addReply(c,shared.cone);
354 }
355 
356 void sismemberCommand(redisClient *c) {
357     robj *set;
358 
359     if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
360         checkType(c,set,REDIS_SET)) return;
361 
362     c->argv[2] = tryObjectEncoding(c->argv[2]);
363     if (setTypeIsMember(set,c->argv[2]))
364         addReply(c,shared.cone);
365     else
366         addReply(c,shared.czero);
367 }
368 
369 void scardCommand(redisClient *c) {
370     robj *o;
371 
372     if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
373         checkType(c,o,REDIS_SET)) return;
374 
375     addReplyLongLong(c,setTypeSize(o));
376 }
377 
378 void spopCommand(redisClient *c) {
379     robj *set, *ele, *aux;
380     int64_t llele;
381     int encoding;
382 
383     if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
384         checkType(c,set,REDIS_SET)) return;
385 
386     encoding = setTypeRandomElement(set,&ele,&llele);
387     if (encoding == REDIS_ENCODING_INTSET) {
388         ele = createStringObjectFromLongLong(llele);
389         set->ptr = intsetRemove(set->ptr,llele,NULL);
390     } else {
391         incrRefCount(ele);
392         setTypeRemove(set,ele);
393     }
394     notifyKeyspaceEvent("spop",c->argv[1],c->db->id);
395 
396     /* Replicate/AOF this command as an SREM operation */
397     aux = createStringObject("SREM",4);
398     rewriteClientCommandVector(c,3,aux,c->argv[1],ele);
399     decrRefCount(ele);
400     decrRefCount(aux);
401 
402     addReplyBulk(c,ele);
403     if (setTypeSize(set) == 0) {
404         dbDelete(c->db,c->argv[1]);
405         notifyKeyspaceEvent("del",c->argv[1],c->db->id);
406     }
407     signalModifiedKey(c->db,c->argv[1]);
408     server.dirty++;
409 }
410 
411 /* handle the "SRANDMEMBER key <count>" variant. The normal version of the
412  * command is handled by the srandmemberCommand() function itself. */
413 
414 /* How many times bigger should be the set compared to the requested size
415  * for us to don't use the "remove elements" strategy? Read later in the
416  * implementation for more info. */
417 #define SRANDMEMBER_SUB_STRATEGY_MUL 3
418 
419 void srandmemberWithCountCommand(redisClient *c) {
420     long l;
421     unsigned long count, size;
422     int uniq = 1;
423     robj *set, *ele;
424     int64_t llele;
425     int encoding;
426 
427     dict *d;
428 
429     if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != REDIS_OK) return;
430     if (l >= 0) {
431         count = (unsigned) l;
432     } else {
433         /* A negative count means: return the same elements multiple times
434          * (i.e. don't remove the extracted element after every extraction). */
435         count = -l;
436         uniq = 0;
437     }
438 
439     if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk))
440         == NULL || checkType(c,set,REDIS_SET)) return;
441     size = setTypeSize(set);
442 
443     /* If count is zero, serve it ASAP to avoid special cases later. */
444     if (count == 0) {
445         addReply(c,shared.emptymultibulk);
446         return;
447     }
448 
449     /* CASE 1: The count was negative, so the extraction method is just:
450      * "return N random elements" sampling the whole set every time.
451      * This case is trivial and can be served without auxiliary data
452      * structures. */
453     if (!uniq) {
454         addReplyMultiBulkLen(c,count);
455         while(count--) {
456             encoding = setTypeRandomElement(set,&ele,&llele);
457             if (encoding == REDIS_ENCODING_INTSET) {
458                 addReplyBulkLongLong(c,llele);
459             } else {
460                 addReplyBulk(c,ele);
461             }
462         }
463         return;
464     }
465 
466     /* CASE 2:
467      * The number of requested elements is greater than the number of
468      * elements inside the set: simply return the whole set. */
469     if (count >= size) {
470         sunionDiffGenericCommand(c,c->argv,c->argc-1,NULL,REDIS_OP_UNION);
471         return;
472     }
473 
474     /* For CASE 3 and CASE 4 we need an auxiliary dictionary. */
475     d = dictCreate(&setDictType,NULL);
476 
477     /* CASE 3:
478      * The number of elements inside the set is not greater than
479      * SRANDMEMBER_SUB_STRATEGY_MUL times the number of requested elements.
480      * In this case we create a set from scratch with all the elements, and
481      * subtract random elements to reach the requested number of elements.
482      *
483      * This is done because if the number of requsted elements is just
484      * a bit less than the number of elements in the set, the natural approach
485      * used into CASE 3 is highly inefficient. */
486     if (count*SRANDMEMBER_SUB_STRATEGY_MUL > size) {
487         setTypeIterator *si;
488 
489         /* Add all the elements into the temporary dictionary. */
490         si = setTypeInitIterator(set);
491         while((encoding = setTypeNext(si,&ele,&llele)) != -1) {
492             int retval;
493 
494             if (encoding == REDIS_ENCODING_INTSET) {
495                 retval = dictAdd(d,createStringObjectFromLongLong(llele),NULL);
496             } else if (ele->encoding == REDIS_ENCODING_RAW) {
497                 retval = dictAdd(d,dupStringObject(ele),NULL);
498             } else if (ele->encoding == REDIS_ENCODING_INT) {
499                 retval = dictAdd(d,
500                     createStringObjectFromLongLong((long)ele->ptr),NULL);
501             }
502             redisAssert(retval == DICT_OK);
503         }
504         setTypeReleaseIterator(si);
505         redisAssert(dictSize(d) == size);
506 
507         /* Remove random elements to reach the right count. */
508         while(size > count) {
509             dictEntry *de;
510 
511             de = dictGetRandomKey(d);
512             dictDelete(d,dictGetKey(de));
513             size--;
514         }
515     }
516 
517     /* CASE 4: We have a big set compared to the requested number of elements.
518      * In this case we can simply get random elements from the set and add
519      * to the temporary set, trying to eventually get enough unique elements
520      * to reach the specified count. */
521     else {
522         unsigned long added = 0;
523 
524         while(added < count) {
525             encoding = setTypeRandomElement(set,&ele,&llele);
526             if (encoding == REDIS_ENCODING_INTSET) {
527                 ele = createStringObjectFromLongLong(llele);
528             } else if (ele->encoding == REDIS_ENCODING_RAW) {
529                 ele = dupStringObject(ele);
530             } else if (ele->encoding == REDIS_ENCODING_INT) {
531                 ele = createStringObjectFromLongLong((long)ele->ptr);
532             }
533             /* Try to add the object to the dictionary. If it already exists
534              * free it, otherwise increment the number of objects we have
535              * in the result dictionary. */
536             if (dictAdd(d,ele,NULL) == DICT_OK)
537                 added++;
538             else
539                 decrRefCount(ele);
540         }
541     }
542 
543     /* CASE 3 & 4: send the result to the user. */
544     {
545         dictIterator *di;
546         dictEntry *de;
547 
548         addReplyMultiBulkLen(c,count);
549         di = dictGetIterator(d);
550         while((de = dictNext(di)) != NULL)
551             addReplyBulk(c,dictGetKey(de));
552         dictReleaseIterator(di);
553         dictRelease(d);
554     }
555 }
556 
557 void srandmemberCommand(redisClient *c) {
558     robj *set, *ele;
559     int64_t llele;
560     int encoding;
561 
562     if (c->argc == 3) {
563         srandmemberWithCountCommand(c);
564         return;
565     } else if (c->argc > 3) {
566         addReply(c,shared.syntaxerr);
567         return;
568     }
569 
570     if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
571         checkType(c,set,REDIS_SET)) return;
572 
573     encoding = setTypeRandomElement(set,&ele,&llele);
574     if (encoding == REDIS_ENCODING_INTSET) {
575         addReplyBulkLongLong(c,llele);
576     } else {
577         addReplyBulk(c,ele);
578     }
579 }
580 
581 int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
582     return setTypeSize(*(robj**)s1)-setTypeSize(*(robj**)s2);
583 }
584 
585 /* This is used by SDIFF and in this case we can receive NULL that should
586  * be handled as empty sets. */
587 int qsortCompareSetsByRevCardinality(const void *s1, const void *s2) {
588     robj *o1 = *(robj**)s1, *o2 = *(robj**)s2;
589 
590     return  (o2 ? setTypeSize(o2) : 0) - (o1 ? setTypeSize(o1) : 0);
591 }
592 
593 void sinterGenericCommand(redisClient *c, robj **setkeys, unsigned long setnum, robj *dstkey) {
594     robj **sets = zmalloc(sizeof(robj*)*setnum);
595     setTypeIterator *si;
596     robj *eleobj, *dstset = NULL;
597     int64_t intobj;
598     void *replylen = NULL;
599     unsigned long j, cardinality = 0;
600     int encoding;
601 
602     for (j = 0; j < setnum; j++) {
603         robj *setobj = dstkey ?
604             lookupKeyWrite(c->db,setkeys[j]) :
605             lookupKeyRead(c->db,setkeys[j]);
606         if (!setobj) {
607             zfree(sets);
608             if (dstkey) {
609                 if (dbDelete(c->db,dstkey)) {
610                     signalModifiedKey(c->db,dstkey);
611                     server.dirty++;
612                 }
613                 addReply(c,shared.czero);
614             } else {
615                 addReply(c,shared.emptymultibulk);
616             }
617             return;
618         }
619         if (checkType(c,setobj,REDIS_SET)) {
620             zfree(sets);
621             return;
622         }
623         sets[j] = setobj;
624     }
625     /* Sort sets from the smallest to largest, this will improve our
626      * algorithm's performance */
627     qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality);
628 
629     /* The first thing we should output is the total number of elements...
630      * since this is a multi-bulk write, but at this stage we don't know
631      * the intersection set size, so we use a trick, append an empty object
632      * to the output list and save the pointer to later modify it with the
633      * right length */
634     if (!dstkey) {
635         replylen = addDeferredMultiBulkLength(c);
636     } else {
637         /* If we have a target key where to store the resulting set
638          * create this key with an empty set inside */
639         dstset = createIntsetObject();
640     }
641 
642     /* Iterate all the elements of the first (smallest) set, and test
643      * the element against all the other sets, if at least one set does
644      * not include the element it is discarded */
645     si = setTypeInitIterator(sets[0]);
646     while((encoding = setTypeNext(si,&eleobj,&intobj)) != -1) {
647         for (j = 1; j < setnum; j++) {
648             if (sets[j] == sets[0]) continue;
649             if (encoding == REDIS_ENCODING_INTSET) {
650                 /* intset with intset is simple... and fast */
651                 if (sets[j]->encoding == REDIS_ENCODING_INTSET &&
652                     !intsetFind((intset*)sets[j]->ptr,intobj))
653                 {
654                     break;
655                 /* in order to compare an integer with an object we
656                  * have to use the generic function, creating an object
657                  * for this */
658                 } else if (sets[j]->encoding == REDIS_ENCODING_HT) {
659                     eleobj = createStringObjectFromLongLong(intobj);
660                     if (!setTypeIsMember(sets[j],eleobj)) {
661                         decrRefCount(eleobj);
662                         break;
663                     }
664                     decrRefCount(eleobj);
665                 }
666             } else if (encoding == REDIS_ENCODING_HT) {
667                 /* Optimization... if the source object is integer
668                  * encoded AND the target set is an intset, we can get
669                  * a much faster path. */
670                 if (eleobj->encoding == REDIS_ENCODING_INT &&
671                     sets[j]->encoding == REDIS_ENCODING_INTSET &&
672                     !intsetFind((intset*)sets[j]->ptr,(long)eleobj->ptr))
673                 {
674                     break;
675                 /* else... object to object check is easy as we use the
676                  * type agnostic API here. */
677                 } else if (!setTypeIsMember(sets[j],eleobj)) {
678                     break;
679                 }
680             }
681         }
682 
683         /* Only take action when all sets contain the member */
684         if (j == setnum) {
685             if (!dstkey) {
686                 if (encoding == REDIS_ENCODING_HT)
687                     addReplyBulk(c,eleobj);
688                 else
689                     addReplyBulkLongLong(c,intobj);
690                 cardinality++;
691             } else {
692                 if (encoding == REDIS_ENCODING_INTSET) {
693                     eleobj = createStringObjectFromLongLong(intobj);
694                     setTypeAdd(dstset,eleobj);
695                     decrRefCount(eleobj);
696                 } else {
697                     setTypeAdd(dstset,eleobj);
698                 }
699             }
700         }
701     }
702     setTypeReleaseIterator(si);
703 
704     if (dstkey) {
705         /* Store the resulting set into the target, if the intersection
706          * is not an empty set. */
707         dbDelete(c->db,dstkey);
708         if (setTypeSize(dstset) > 0) {
709             dbAdd(c->db,dstkey,dstset);
710             addReplyLongLong(c,setTypeSize(dstset));
711             notifyKeyspaceEvent("sinterstore",dstkey,c->db->id);
712         } else {
713             decrRefCount(dstset);
714             addReply(c,shared.czero);
715         }
716         signalModifiedKey(c->db,dstkey);
717         server.dirty++;
718     } else {
719         setDeferredMultiBulkLength(c,replylen,cardinality);
720     }
721     zfree(sets);
722 }
723 
724 void sinterCommand(redisClient *c) {
725     sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
726 }
727 
728 void sinterstoreCommand(redisClient *c) {
729     sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
730 }
731 
732 #define REDIS_OP_UNION 0
733 #define REDIS_OP_DIFF 1
734 #define REDIS_OP_INTER 2
735 
736 void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op) {
737     robj **sets = zmalloc(sizeof(robj*)*setnum);
738     setTypeIterator *si;
739     robj *ele, *dstset = NULL;
740     int j, cardinality = 0;
741     int diff_algo = 1;
742 
743     for (j = 0; j < setnum; j++) {
744         robj *setobj = dstkey ?
745             lookupKeyWrite(c->db,setkeys[j]) :
746             lookupKeyRead(c->db,setkeys[j]);
747         if (!setobj) {
748             sets[j] = NULL;
749             continue;
750         }
751         if (checkType(c,setobj,REDIS_SET)) {
752             zfree(sets);
753             return;
754         }
755         sets[j] = setobj;
756     }
757 
758     /* Select what DIFF algorithm to use.
759      *
760      * Algorithm 1 is O(N*M) where N is the size of the element first set
761      * and M the total number of sets.
762      *
763      * Algorithm 2 is O(N) where N is the total number of elements in all
764      * the sets.
765      *
766      * We compute what is the best bet with the current input here. */
767     if (op == REDIS_OP_DIFF && sets[0]) {
768         long long algo_one_work = 0, algo_two_work = 0;
769 
770         for (j = 0; j < setnum; j++) {
771             if (sets[j] == NULL) continue;
772 
773             algo_one_work += setTypeSize(sets[0]);
774             algo_two_work += setTypeSize(sets[j]);
775         }
776 
777         /* Algorithm 1 has better constant times and performs less operations
778          * if there are elements in common. Give it some advantage. */
779         algo_one_work /= 2;
780         diff_algo = (algo_one_work <= algo_two_work) ? 1 : 2;
781 
782         if (diff_algo == 1 && setnum > 1) {
783             /* With algorithm 1 it is better to order the sets to subtract
784              * by decreasing size, so that we are more likely to find
785              * duplicated elements ASAP. */
786             qsort(sets+1,setnum-1,sizeof(robj*),
787                 qsortCompareSetsByRevCardinality);
788         }
789     }
790 
791     /* We need a temp set object to store our union. If the dstkey
792      * is not NULL (that is, we are inside an SUNIONSTORE operation) then
793      * this set object will be the resulting object to set into the target key*/
794     dstset = createIntsetObject();
795 
796     if (op == REDIS_OP_UNION) {
797         /* Union is trivial, just add every element of every set to the
798          * temporary set. */
799         for (j = 0; j < setnum; j++) {
800             if (!sets[j]) continue; /* non existing keys are like empty sets */
801 
802             si = setTypeInitIterator(sets[j]);
803             while((ele = setTypeNextObject(si)) != NULL) {
804                 if (setTypeAdd(dstset,ele)) cardinality++;
805                 decrRefCount(ele);
806             }
807             setTypeReleaseIterator(si);
808         }
809     } else if (op == REDIS_OP_DIFF && sets[0] && diff_algo == 1) {
810         /* DIFF Algorithm 1:
811          *
812          * We perform the diff by iterating all the elements of the first set,
813          * and only adding it to the target set if the element does not exist
814          * into all the other sets.
815          *
816          * This way we perform at max N*M operations, where N is the size of
817          * the first set, and M the number of sets. */
818         si = setTypeInitIterator(sets[0]);
819         while((ele = setTypeNextObject(si)) != NULL) {
820             for (j = 1; j < setnum; j++) {
821                 if (!sets[j]) continue; /* no key is an empty set. */
822                 if (setTypeIsMember(sets[j],ele)) break;
823             }
824             if (j == setnum) {
825                 /* There is no other set with this element. Add it. */
826                 setTypeAdd(dstset,ele);
827                 cardinality++;
828             }
829             decrRefCount(ele);
830         }
831         setTypeReleaseIterator(si);
832     } else if (op == REDIS_OP_DIFF && sets[0] && diff_algo == 2) {
833         /* DIFF Algorithm 2:
834          *
835          * Add all the elements of the first set to the auxiliary set.
836          * Then remove all the elements of all the next sets from it.
837          *
838          * This is O(N) where N is the sum of all the elements in every
839          * set. */
840         for (j = 0; j < setnum; j++) {
841             if (!sets[j]) continue; /* non existing keys are like empty sets */
842 
843             si = setTypeInitIterator(sets[j]);
844             while((ele = setTypeNextObject(si)) != NULL) {
845                 if (j == 0) {
846                     if (setTypeAdd(dstset,ele)) cardinality++;
847                 } else {
848                     if (setTypeRemove(dstset,ele)) cardinality--;
849                 }
850                 decrRefCount(ele);
851             }
852             setTypeReleaseIterator(si);
853 
854             /* Exit if result set is empty as any additional removal
855              * of elements will have no effect. */
856             if (cardinality == 0) break;
857         }
858     }
859 
860     /* Output the content of the resulting set, if not in STORE mode */
861     if (!dstkey) {
862         addReplyMultiBulkLen(c,cardinality);
863         si = setTypeInitIterator(dstset);
864         while((ele = setTypeNextObject(si)) != NULL) {
865             addReplyBulk(c,ele);
866             decrRefCount(ele);
867         }
868         setTypeReleaseIterator(si);
869         decrRefCount(dstset);
870     } else {
871         /* If we have a target key where to store the resulting set
872          * create this key with the result set inside */
873         dbDelete(c->db,dstkey);
874         if (setTypeSize(dstset) > 0) {
875             dbAdd(c->db,dstkey,dstset);
876             addReplyLongLong(c,setTypeSize(dstset));
877             notifyKeyspaceEvent(
878                 op == REDIS_OP_UNION ? "sunionstore" : "sdiffstore",
879                 dstkey,c->db->id);
880         } else {
881             decrRefCount(dstset);
882             addReply(c,shared.czero);
883         }
884         signalModifiedKey(c->db,dstkey);
885         server.dirty++;
886     }
887     zfree(sets);
888 }
889 
890 void sunionCommand(redisClient *c) {
891     sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
892 }
893 
894 void sunionstoreCommand(redisClient *c) {
895     sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
896 }
897 
898 void sdiffCommand(redisClient *c) {
899     sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
900 }
901 
902 void sdiffstoreCommand(redisClient *c) {
903     sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
904 }
905