]> git.saurik.com Git - redis.git/blob - src/t_set.c
fix aof and digest code to work with dual set encoding
[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 (getLongLongFromObject(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 (getLongLongFromObject(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 *subject, robj *value) {
51 long long llval;
52 if (subject->encoding == REDIS_ENCODING_HT) {
53 if (dictDelete(subject->ptr,value) == DICT_OK) {
54 if (htNeedsResize(subject->ptr)) dictResize(subject->ptr);
55 return 1;
56 }
57 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
58 if (getLongLongFromObject(value,&llval) == REDIS_OK) {
59 uint8_t success;
60 subject->ptr = intsetRemove(subject->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 (getLongLongFromObject(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 setIterator *setTypeInitIterator(robj *subject) {
84 setIterator *si = zmalloc(sizeof(setIterator));
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(setIterator *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, or NULL when the end is reached. This object will have its
105 * refcount incremented, so the caller needs to take care of this. */
106 robj *setTypeNext(setIterator *si) {
107 robj *ret = NULL;
108 if (si->encoding == REDIS_ENCODING_HT) {
109 dictEntry *de = dictNext(si->di);
110 if (de != NULL) {
111 ret = dictGetEntryKey(de);
112 incrRefCount(ret);
113 }
114 } else if (si->encoding == REDIS_ENCODING_INTSET) {
115 long long llval;
116 if (intsetGet(si->subject->ptr,si->ii++,&llval))
117 ret = createStringObjectFromLongLong(llval);
118 }
119 return ret;
120 }
121
122
123 /* Return random element from set. The returned object will always have
124 * an incremented refcount. */
125 robj *setTypeRandomElement(robj *subject) {
126 robj *ret = NULL;
127 if (subject->encoding == REDIS_ENCODING_HT) {
128 dictEntry *de = dictGetRandomKey(subject->ptr);
129 ret = dictGetEntryKey(de);
130 incrRefCount(ret);
131 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
132 long long llval = intsetRandom(subject->ptr);
133 ret = createStringObjectFromLongLong(llval);
134 } else {
135 redisPanic("Unknown set encoding");
136 }
137 return ret;
138 }
139
140 unsigned long setTypeSize(robj *subject) {
141 if (subject->encoding == REDIS_ENCODING_HT) {
142 return dictSize((dict*)subject->ptr);
143 } else if (subject->encoding == REDIS_ENCODING_INTSET) {
144 return intsetLen((intset*)subject->ptr);
145 } else {
146 redisPanic("Unknown set encoding");
147 }
148 }
149
150 /* Convert the set to specified encoding. The resulting dict (when converting
151 * to a hashtable) is presized to hold the number of elements in the original
152 * set. */
153 void setTypeConvert(robj *subject, int enc) {
154 setIterator *si;
155 robj *element;
156 redisAssert(subject->type == REDIS_SET);
157
158 if (enc == REDIS_ENCODING_HT) {
159 dict *d = dictCreate(&setDictType,NULL);
160 /* Presize the dict to avoid rehashing */
161 dictExpand(d,intsetLen(subject->ptr));
162
163 /* setTypeGet returns a robj with incremented refcount */
164 si = setTypeInitIterator(subject);
165 while ((element = setTypeNext(si)) != NULL)
166 redisAssert(dictAdd(d,element,NULL) == DICT_OK);
167 setTypeReleaseIterator(si);
168
169 subject->encoding = REDIS_ENCODING_HT;
170 zfree(subject->ptr);
171 subject->ptr = d;
172 } else {
173 redisPanic("Unsupported set conversion");
174 }
175 }
176
177 void saddCommand(redisClient *c) {
178 robj *set;
179
180 set = lookupKeyWrite(c->db,c->argv[1]);
181 if (set == NULL) {
182 set = setTypeCreate(c->argv[2]);
183 dbAdd(c->db,c->argv[1],set);
184 } else {
185 if (set->type != REDIS_SET) {
186 addReply(c,shared.wrongtypeerr);
187 return;
188 }
189 }
190 if (setTypeAdd(set,c->argv[2])) {
191 server.dirty++;
192 addReply(c,shared.cone);
193 } else {
194 addReply(c,shared.czero);
195 }
196 }
197
198 void sremCommand(redisClient *c) {
199 robj *set;
200
201 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
202 checkType(c,set,REDIS_SET)) return;
203
204 if (setTypeRemove(set,c->argv[2])) {
205 if (setTypeSize(set) == 0) dbDelete(c->db,c->argv[1]);
206 server.dirty++;
207 addReply(c,shared.cone);
208 } else {
209 addReply(c,shared.czero);
210 }
211 }
212
213 void smoveCommand(redisClient *c) {
214 robj *srcset, *dstset, *ele;
215 srcset = lookupKeyWrite(c->db,c->argv[1]);
216 dstset = lookupKeyWrite(c->db,c->argv[2]);
217 ele = c->argv[3];
218
219 /* If the source key does not exist return 0 */
220 if (srcset == NULL) {
221 addReply(c,shared.czero);
222 return;
223 }
224
225 /* If the source key has the wrong type, or the destination key
226 * is set and has the wrong type, return with an error. */
227 if (checkType(c,srcset,REDIS_SET) ||
228 (dstset && checkType(c,dstset,REDIS_SET))) return;
229
230 /* If srcset and dstset are equal, SMOVE is a no-op */
231 if (srcset == dstset) {
232 addReply(c,shared.cone);
233 return;
234 }
235
236 /* If the element cannot be removed from the src set, return 0. */
237 if (!setTypeRemove(srcset,ele)) {
238 addReply(c,shared.czero);
239 return;
240 }
241
242 /* Remove the src set from the database when empty */
243 if (setTypeSize(srcset) == 0) dbDelete(c->db,c->argv[1]);
244 server.dirty++;
245
246 /* Create the destination set when it doesn't exist */
247 if (!dstset) {
248 dstset = setTypeCreate(ele);
249 dbAdd(c->db,c->argv[2],dstset);
250 }
251
252 /* An extra key has changed when ele was successfully added to dstset */
253 if (setTypeAdd(dstset,ele)) server.dirty++;
254 addReply(c,shared.cone);
255 }
256
257 void sismemberCommand(redisClient *c) {
258 robj *set;
259
260 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
261 checkType(c,set,REDIS_SET)) return;
262
263 if (setTypeIsMember(set,c->argv[2]))
264 addReply(c,shared.cone);
265 else
266 addReply(c,shared.czero);
267 }
268
269 void scardCommand(redisClient *c) {
270 robj *o;
271
272 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
273 checkType(c,o,REDIS_SET)) return;
274
275 addReplyUlong(c,setTypeSize(o));
276 }
277
278 void spopCommand(redisClient *c) {
279 robj *set, *ele;
280
281 if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
282 checkType(c,set,REDIS_SET)) return;
283
284 ele = setTypeRandomElement(set);
285 if (ele == NULL) {
286 addReply(c,shared.nullbulk);
287 } else {
288 setTypeRemove(set,ele);
289 addReplyBulk(c,ele);
290 decrRefCount(ele);
291 if (setTypeSize(set) == 0) dbDelete(c->db,c->argv[1]);
292 server.dirty++;
293 }
294 }
295
296 void srandmemberCommand(redisClient *c) {
297 robj *set, *ele;
298
299 if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
300 checkType(c,set,REDIS_SET)) return;
301
302 ele = setTypeRandomElement(set);
303 if (ele == NULL) {
304 addReply(c,shared.nullbulk);
305 } else {
306 addReplyBulk(c,ele);
307 decrRefCount(ele);
308 }
309 }
310
311 int qsortCompareSetsByCardinality(const void *s1, const void *s2) {
312 return setTypeSize(*(robj**)s1)-setTypeSize(*(robj**)s2);
313 }
314
315 void sinterGenericCommand(redisClient *c, robj **setkeys, unsigned long setnum, robj *dstkey) {
316 robj **sets = zmalloc(sizeof(robj*)*setnum);
317 setIterator *si;
318 robj *ele, *lenobj = NULL, *dstset = NULL;
319 unsigned long j, cardinality = 0;
320
321 for (j = 0; j < setnum; j++) {
322 robj *setobj = dstkey ?
323 lookupKeyWrite(c->db,setkeys[j]) :
324 lookupKeyRead(c->db,setkeys[j]);
325 if (!setobj) {
326 zfree(sets);
327 if (dstkey) {
328 if (dbDelete(c->db,dstkey))
329 server.dirty++;
330 addReply(c,shared.czero);
331 } else {
332 addReply(c,shared.emptymultibulk);
333 }
334 return;
335 }
336 if (checkType(c,setobj,REDIS_SET)) {
337 zfree(sets);
338 return;
339 }
340 sets[j] = setobj;
341 }
342 /* Sort sets from the smallest to largest, this will improve our
343 * algorithm's performace */
344 qsort(sets,setnum,sizeof(robj*),qsortCompareSetsByCardinality);
345
346 /* The first thing we should output is the total number of elements...
347 * since this is a multi-bulk write, but at this stage we don't know
348 * the intersection set size, so we use a trick, append an empty object
349 * to the output list and save the pointer to later modify it with the
350 * right length */
351 if (!dstkey) {
352 lenobj = createObject(REDIS_STRING,NULL);
353 addReply(c,lenobj);
354 decrRefCount(lenobj);
355 } else {
356 /* If we have a target key where to store the resulting set
357 * create this key with an empty set inside */
358 dstset = createIntsetObject();
359 }
360
361 /* Iterate all the elements of the first (smallest) set, and test
362 * the element against all the other sets, if at least one set does
363 * not include the element it is discarded */
364 si = setTypeInitIterator(sets[0]);
365 while((ele = setTypeNext(si)) != NULL) {
366 for (j = 1; j < setnum; j++)
367 if (!setTypeIsMember(sets[j],ele)) break;
368
369 /* Only take action when all sets contain the member */
370 if (j == setnum) {
371 if (!dstkey) {
372 addReplyBulk(c,ele);
373 cardinality++;
374 } else {
375 setTypeAdd(dstset,ele);
376 }
377 }
378 decrRefCount(ele);
379 }
380 setTypeReleaseIterator(si);
381
382 if (dstkey) {
383 /* Store the resulting set into the target, if the intersection
384 * is not an empty set. */
385 dbDelete(c->db,dstkey);
386 if (setTypeSize(dstset) > 0) {
387 dbAdd(c->db,dstkey,dstset);
388 addReplyLongLong(c,setTypeSize(dstset));
389 } else {
390 decrRefCount(dstset);
391 addReply(c,shared.czero);
392 }
393 server.dirty++;
394 } else {
395 lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n",cardinality);
396 }
397 zfree(sets);
398 }
399
400 void sinterCommand(redisClient *c) {
401 sinterGenericCommand(c,c->argv+1,c->argc-1,NULL);
402 }
403
404 void sinterstoreCommand(redisClient *c) {
405 sinterGenericCommand(c,c->argv+2,c->argc-2,c->argv[1]);
406 }
407
408 #define REDIS_OP_UNION 0
409 #define REDIS_OP_DIFF 1
410 #define REDIS_OP_INTER 2
411
412 void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op) {
413 robj **sets = zmalloc(sizeof(robj*)*setnum);
414 setIterator *si;
415 robj *ele, *dstset = NULL;
416 int j, cardinality = 0;
417
418 for (j = 0; j < setnum; j++) {
419 robj *setobj = dstkey ?
420 lookupKeyWrite(c->db,setkeys[j]) :
421 lookupKeyRead(c->db,setkeys[j]);
422 if (!setobj) {
423 sets[j] = NULL;
424 continue;
425 }
426 if (checkType(c,setobj,REDIS_SET)) {
427 zfree(sets);
428 return;
429 }
430 sets[j] = setobj;
431 }
432
433 /* We need a temp set object to store our union. If the dstkey
434 * is not NULL (that is, we are inside an SUNIONSTORE operation) then
435 * this set object will be the resulting object to set into the target key*/
436 dstset = createIntsetObject();
437
438 /* Iterate all the elements of all the sets, add every element a single
439 * time to the result set */
440 for (j = 0; j < setnum; j++) {
441 if (op == REDIS_OP_DIFF && j == 0 && !sets[j]) break; /* result set is empty */
442 if (!sets[j]) continue; /* non existing keys are like empty sets */
443
444 si = setTypeInitIterator(sets[j]);
445 while((ele = setTypeNext(si)) != NULL) {
446 if (op == REDIS_OP_UNION || j == 0) {
447 if (setTypeAdd(dstset,ele)) {
448 cardinality++;
449 }
450 } else if (op == REDIS_OP_DIFF) {
451 if (setTypeRemove(dstset,ele)) {
452 cardinality--;
453 }
454 }
455 decrRefCount(ele);
456 }
457 setTypeReleaseIterator(si);
458
459 /* Exit when result set is empty. */
460 if (op == REDIS_OP_DIFF && cardinality == 0) break;
461 }
462
463 /* Output the content of the resulting set, if not in STORE mode */
464 if (!dstkey) {
465 addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n",cardinality));
466 si = setTypeInitIterator(dstset);
467 while((ele = setTypeNext(si)) != NULL) {
468 addReplyBulk(c,ele);
469 decrRefCount(ele);
470 }
471 setTypeReleaseIterator(si);
472 decrRefCount(dstset);
473 } else {
474 /* If we have a target key where to store the resulting set
475 * create this key with the result set inside */
476 dbDelete(c->db,dstkey);
477 if (setTypeSize(dstset) > 0) {
478 dbAdd(c->db,dstkey,dstset);
479 addReplyLongLong(c,setTypeSize(dstset));
480 } else {
481 decrRefCount(dstset);
482 addReply(c,shared.czero);
483 }
484 server.dirty++;
485 }
486 zfree(sets);
487 }
488
489 void sunionCommand(redisClient *c) {
490 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_UNION);
491 }
492
493 void sunionstoreCommand(redisClient *c) {
494 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_UNION);
495 }
496
497 void sdiffCommand(redisClient *c) {
498 sunionDiffGenericCommand(c,c->argv+1,c->argc-1,NULL,REDIS_OP_DIFF);
499 }
500
501 void sdiffstoreCommand(redisClient *c) {
502 sunionDiffGenericCommand(c,c->argv+2,c->argc-2,c->argv[1],REDIS_OP_DIFF);
503 }