]>
Commit | Line | Data |
---|---|---|
e2641e09 | 1 | #include "redis.h" |
2 | ||
3 | #include <math.h> | |
4 | ||
5 | /*----------------------------------------------------------------------------- | |
6 | * Sorted set API | |
7 | *----------------------------------------------------------------------------*/ | |
8 | ||
9 | /* ZSETs are ordered sets using two data structures to hold the same elements | |
10 | * in order to get O(log(N)) INSERT and REMOVE operations into a sorted | |
11 | * data structure. | |
12 | * | |
13 | * The elements are added to an hash table mapping Redis objects to scores. | |
14 | * At the same time the elements are added to a skip list mapping scores | |
15 | * to Redis objects (so objects are sorted by scores in this "view"). */ | |
16 | ||
17 | /* This skiplist implementation is almost a C translation of the original | |
18 | * algorithm described by William Pugh in "Skip Lists: A Probabilistic | |
19 | * Alternative to Balanced Trees", modified in three ways: | |
20 | * a) this implementation allows for repeated values. | |
21 | * b) the comparison is not just by key (our 'score') but by satellite data. | |
22 | * c) there is a back pointer, so it's a doubly linked list with the back | |
23 | * pointers being only at "level 1". This allows to traverse the list | |
24 | * from tail to head, useful for ZREVRANGE. */ | |
25 | ||
26 | zskiplistNode *zslCreateNode(int level, double score, robj *obj) { | |
27 | zskiplistNode *zn = zmalloc(sizeof(*zn)); | |
28 | ||
29 | zn->forward = zmalloc(sizeof(zskiplistNode*) * level); | |
30 | if (level > 1) | |
31 | zn->span = zmalloc(sizeof(unsigned int) * (level - 1)); | |
32 | else | |
33 | zn->span = NULL; | |
34 | zn->score = score; | |
35 | zn->obj = obj; | |
36 | return zn; | |
37 | } | |
38 | ||
39 | zskiplist *zslCreate(void) { | |
40 | int j; | |
41 | zskiplist *zsl; | |
42 | ||
43 | zsl = zmalloc(sizeof(*zsl)); | |
44 | zsl->level = 1; | |
45 | zsl->length = 0; | |
46 | zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL); | |
47 | for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) { | |
48 | zsl->header->forward[j] = NULL; | |
49 | ||
50 | /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */ | |
51 | if (j < ZSKIPLIST_MAXLEVEL-1) | |
52 | zsl->header->span[j] = 0; | |
53 | } | |
54 | zsl->header->backward = NULL; | |
55 | zsl->tail = NULL; | |
56 | return zsl; | |
57 | } | |
58 | ||
59 | void zslFreeNode(zskiplistNode *node) { | |
60 | decrRefCount(node->obj); | |
61 | zfree(node->forward); | |
62 | zfree(node->span); | |
63 | zfree(node); | |
64 | } | |
65 | ||
66 | void zslFree(zskiplist *zsl) { | |
67 | zskiplistNode *node = zsl->header->forward[0], *next; | |
68 | ||
69 | zfree(zsl->header->forward); | |
70 | zfree(zsl->header->span); | |
71 | zfree(zsl->header); | |
72 | while(node) { | |
73 | next = node->forward[0]; | |
74 | zslFreeNode(node); | |
75 | node = next; | |
76 | } | |
77 | zfree(zsl); | |
78 | } | |
79 | ||
80 | int zslRandomLevel(void) { | |
81 | int level = 1; | |
82 | while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF)) | |
83 | level += 1; | |
84 | return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL; | |
85 | } | |
86 | ||
87 | void zslInsert(zskiplist *zsl, double score, robj *obj) { | |
88 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
89 | unsigned int rank[ZSKIPLIST_MAXLEVEL]; | |
90 | int i, level; | |
91 | ||
92 | x = zsl->header; | |
93 | for (i = zsl->level-1; i >= 0; i--) { | |
94 | /* store rank that is crossed to reach the insert position */ | |
95 | rank[i] = i == (zsl->level-1) ? 0 : rank[i+1]; | |
96 | ||
97 | while (x->forward[i] && | |
98 | (x->forward[i]->score < score || | |
99 | (x->forward[i]->score == score && | |
100 | compareStringObjects(x->forward[i]->obj,obj) < 0))) { | |
101 | rank[i] += i > 0 ? x->span[i-1] : 1; | |
102 | x = x->forward[i]; | |
103 | } | |
104 | update[i] = x; | |
105 | } | |
106 | /* we assume the key is not already inside, since we allow duplicated | |
107 | * scores, and the re-insertion of score and redis object should never | |
108 | * happpen since the caller of zslInsert() should test in the hash table | |
109 | * if the element is already inside or not. */ | |
110 | level = zslRandomLevel(); | |
111 | if (level > zsl->level) { | |
112 | for (i = zsl->level; i < level; i++) { | |
113 | rank[i] = 0; | |
114 | update[i] = zsl->header; | |
115 | update[i]->span[i-1] = zsl->length; | |
116 | } | |
117 | zsl->level = level; | |
118 | } | |
119 | x = zslCreateNode(level,score,obj); | |
120 | for (i = 0; i < level; i++) { | |
121 | x->forward[i] = update[i]->forward[i]; | |
122 | update[i]->forward[i] = x; | |
123 | ||
124 | /* update span covered by update[i] as x is inserted here */ | |
125 | if (i > 0) { | |
126 | x->span[i-1] = update[i]->span[i-1] - (rank[0] - rank[i]); | |
127 | update[i]->span[i-1] = (rank[0] - rank[i]) + 1; | |
128 | } | |
129 | } | |
130 | ||
131 | /* increment span for untouched levels */ | |
132 | for (i = level; i < zsl->level; i++) { | |
133 | update[i]->span[i-1]++; | |
134 | } | |
135 | ||
136 | x->backward = (update[0] == zsl->header) ? NULL : update[0]; | |
137 | if (x->forward[0]) | |
138 | x->forward[0]->backward = x; | |
139 | else | |
140 | zsl->tail = x; | |
141 | zsl->length++; | |
142 | } | |
143 | ||
144 | /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */ | |
145 | void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) { | |
146 | int i; | |
147 | for (i = 0; i < zsl->level; i++) { | |
148 | if (update[i]->forward[i] == x) { | |
149 | if (i > 0) { | |
150 | update[i]->span[i-1] += x->span[i-1] - 1; | |
151 | } | |
152 | update[i]->forward[i] = x->forward[i]; | |
153 | } else { | |
154 | /* invariant: i > 0, because update[0]->forward[0] | |
155 | * is always equal to x */ | |
156 | update[i]->span[i-1] -= 1; | |
157 | } | |
158 | } | |
159 | if (x->forward[0]) { | |
160 | x->forward[0]->backward = x->backward; | |
161 | } else { | |
162 | zsl->tail = x->backward; | |
163 | } | |
164 | while(zsl->level > 1 && zsl->header->forward[zsl->level-1] == NULL) | |
165 | zsl->level--; | |
166 | zsl->length--; | |
167 | } | |
168 | ||
169 | /* Delete an element with matching score/object from the skiplist. */ | |
170 | int zslDelete(zskiplist *zsl, double score, robj *obj) { | |
171 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
172 | int i; | |
173 | ||
174 | x = zsl->header; | |
175 | for (i = zsl->level-1; i >= 0; i--) { | |
176 | while (x->forward[i] && | |
177 | (x->forward[i]->score < score || | |
178 | (x->forward[i]->score == score && | |
179 | compareStringObjects(x->forward[i]->obj,obj) < 0))) | |
180 | x = x->forward[i]; | |
181 | update[i] = x; | |
182 | } | |
183 | /* We may have multiple elements with the same score, what we need | |
184 | * is to find the element with both the right score and object. */ | |
185 | x = x->forward[0]; | |
186 | if (x && score == x->score && equalStringObjects(x->obj,obj)) { | |
187 | zslDeleteNode(zsl, x, update); | |
188 | zslFreeNode(x); | |
189 | return 1; | |
190 | } else { | |
191 | return 0; /* not found */ | |
192 | } | |
193 | return 0; /* not found */ | |
194 | } | |
195 | ||
196 | /* Delete all the elements with score between min and max from the skiplist. | |
197 | * Min and mx are inclusive, so a score >= min || score <= max is deleted. | |
198 | * Note that this function takes the reference to the hash table view of the | |
199 | * sorted set, in order to remove the elements from the hash table too. */ | |
200 | unsigned long zslDeleteRangeByScore(zskiplist *zsl, double min, double max, dict *dict) { | |
201 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
202 | unsigned long removed = 0; | |
203 | int i; | |
204 | ||
205 | x = zsl->header; | |
206 | for (i = zsl->level-1; i >= 0; i--) { | |
207 | while (x->forward[i] && x->forward[i]->score < min) | |
208 | x = x->forward[i]; | |
209 | update[i] = x; | |
210 | } | |
211 | /* We may have multiple elements with the same score, what we need | |
212 | * is to find the element with both the right score and object. */ | |
213 | x = x->forward[0]; | |
214 | while (x && x->score <= max) { | |
215 | zskiplistNode *next = x->forward[0]; | |
216 | zslDeleteNode(zsl, x, update); | |
217 | dictDelete(dict,x->obj); | |
218 | zslFreeNode(x); | |
219 | removed++; | |
220 | x = next; | |
221 | } | |
222 | return removed; /* not found */ | |
223 | } | |
224 | ||
225 | /* Delete all the elements with rank between start and end from the skiplist. | |
226 | * Start and end are inclusive. Note that start and end need to be 1-based */ | |
227 | unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) { | |
228 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
229 | unsigned long traversed = 0, removed = 0; | |
230 | int i; | |
231 | ||
232 | x = zsl->header; | |
233 | for (i = zsl->level-1; i >= 0; i--) { | |
234 | while (x->forward[i] && (traversed + (i > 0 ? x->span[i-1] : 1)) < start) { | |
235 | traversed += i > 0 ? x->span[i-1] : 1; | |
236 | x = x->forward[i]; | |
237 | } | |
238 | update[i] = x; | |
239 | } | |
240 | ||
241 | traversed++; | |
242 | x = x->forward[0]; | |
243 | while (x && traversed <= end) { | |
244 | zskiplistNode *next = x->forward[0]; | |
245 | zslDeleteNode(zsl, x, update); | |
246 | dictDelete(dict,x->obj); | |
247 | zslFreeNode(x); | |
248 | removed++; | |
249 | traversed++; | |
250 | x = next; | |
251 | } | |
252 | return removed; | |
253 | } | |
254 | ||
255 | /* Find the first node having a score equal or greater than the specified one. | |
256 | * Returns NULL if there is no match. */ | |
257 | zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) { | |
258 | zskiplistNode *x; | |
259 | int i; | |
260 | ||
261 | x = zsl->header; | |
262 | for (i = zsl->level-1; i >= 0; i--) { | |
263 | while (x->forward[i] && x->forward[i]->score < score) | |
264 | x = x->forward[i]; | |
265 | } | |
266 | /* We may have multiple elements with the same score, what we need | |
267 | * is to find the element with both the right score and object. */ | |
268 | return x->forward[0]; | |
269 | } | |
270 | ||
271 | /* Find the rank for an element by both score and key. | |
272 | * Returns 0 when the element cannot be found, rank otherwise. | |
273 | * Note that the rank is 1-based due to the span of zsl->header to the | |
274 | * first element. */ | |
275 | unsigned long zslistTypeGetRank(zskiplist *zsl, double score, robj *o) { | |
276 | zskiplistNode *x; | |
277 | unsigned long rank = 0; | |
278 | int i; | |
279 | ||
280 | x = zsl->header; | |
281 | for (i = zsl->level-1; i >= 0; i--) { | |
282 | while (x->forward[i] && | |
283 | (x->forward[i]->score < score || | |
284 | (x->forward[i]->score == score && | |
285 | compareStringObjects(x->forward[i]->obj,o) <= 0))) { | |
286 | rank += i > 0 ? x->span[i-1] : 1; | |
287 | x = x->forward[i]; | |
288 | } | |
289 | ||
290 | /* x might be equal to zsl->header, so test if obj is non-NULL */ | |
291 | if (x->obj && equalStringObjects(x->obj,o)) { | |
292 | return rank; | |
293 | } | |
294 | } | |
295 | return 0; | |
296 | } | |
297 | ||
298 | /* Finds an element by its rank. The rank argument needs to be 1-based. */ | |
299 | zskiplistNode* zslistTypeGetElementByRank(zskiplist *zsl, unsigned long rank) { | |
300 | zskiplistNode *x; | |
301 | unsigned long traversed = 0; | |
302 | int i; | |
303 | ||
304 | x = zsl->header; | |
305 | for (i = zsl->level-1; i >= 0; i--) { | |
306 | while (x->forward[i] && (traversed + (i>0 ? x->span[i-1] : 1)) <= rank) | |
307 | { | |
308 | traversed += i > 0 ? x->span[i-1] : 1; | |
309 | x = x->forward[i]; | |
310 | } | |
311 | if (traversed == rank) { | |
312 | return x; | |
313 | } | |
314 | } | |
315 | return NULL; | |
316 | } | |
317 | ||
318 | /*----------------------------------------------------------------------------- | |
319 | * Sorted set commands | |
320 | *----------------------------------------------------------------------------*/ | |
321 | ||
322 | /* This generic command implements both ZADD and ZINCRBY. | |
323 | * scoreval is the score if the operation is a ZADD (doincrement == 0) or | |
324 | * the increment if the operation is a ZINCRBY (doincrement == 1). */ | |
325 | void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double scoreval, int doincrement) { | |
326 | robj *zsetobj; | |
327 | zset *zs; | |
328 | double *score; | |
329 | ||
330 | if (isnan(scoreval)) { | |
331 | addReplySds(c,sdsnew("-ERR provide score is Not A Number (nan)\r\n")); | |
332 | return; | |
333 | } | |
334 | ||
335 | zsetobj = lookupKeyWrite(c->db,key); | |
336 | if (zsetobj == NULL) { | |
337 | zsetobj = createZsetObject(); | |
338 | dbAdd(c->db,key,zsetobj); | |
339 | } else { | |
340 | if (zsetobj->type != REDIS_ZSET) { | |
341 | addReply(c,shared.wrongtypeerr); | |
342 | return; | |
343 | } | |
344 | } | |
345 | zs = zsetobj->ptr; | |
346 | ||
347 | /* Ok now since we implement both ZADD and ZINCRBY here the code | |
348 | * needs to handle the two different conditions. It's all about setting | |
349 | * '*score', that is, the new score to set, to the right value. */ | |
350 | score = zmalloc(sizeof(double)); | |
351 | if (doincrement) { | |
352 | dictEntry *de; | |
353 | ||
354 | /* Read the old score. If the element was not present starts from 0 */ | |
355 | de = dictFind(zs->dict,ele); | |
356 | if (de) { | |
357 | double *oldscore = dictGetEntryVal(de); | |
358 | *score = *oldscore + scoreval; | |
359 | } else { | |
360 | *score = scoreval; | |
361 | } | |
362 | if (isnan(*score)) { | |
363 | addReplySds(c, | |
364 | sdsnew("-ERR resulting score is Not A Number (nan)\r\n")); | |
365 | zfree(score); | |
366 | /* Note that we don't need to check if the zset may be empty and | |
367 | * should be removed here, as we can only obtain Nan as score if | |
368 | * there was already an element in the sorted set. */ | |
369 | return; | |
370 | } | |
371 | } else { | |
372 | *score = scoreval; | |
373 | } | |
374 | ||
375 | /* What follows is a simple remove and re-insert operation that is common | |
376 | * to both ZADD and ZINCRBY... */ | |
377 | if (dictAdd(zs->dict,ele,score) == DICT_OK) { | |
378 | /* case 1: New element */ | |
379 | incrRefCount(ele); /* added to hash */ | |
380 | zslInsert(zs->zsl,*score,ele); | |
381 | incrRefCount(ele); /* added to skiplist */ | |
382 | server.dirty++; | |
383 | if (doincrement) | |
384 | addReplyDouble(c,*score); | |
385 | else | |
386 | addReply(c,shared.cone); | |
387 | } else { | |
388 | dictEntry *de; | |
389 | double *oldscore; | |
390 | ||
391 | /* case 2: Score update operation */ | |
392 | de = dictFind(zs->dict,ele); | |
393 | redisAssert(de != NULL); | |
394 | oldscore = dictGetEntryVal(de); | |
395 | if (*score != *oldscore) { | |
396 | int deleted; | |
397 | ||
398 | /* Remove and insert the element in the skip list with new score */ | |
399 | deleted = zslDelete(zs->zsl,*oldscore,ele); | |
400 | redisAssert(deleted != 0); | |
401 | zslInsert(zs->zsl,*score,ele); | |
402 | incrRefCount(ele); | |
403 | /* Update the score in the hash table */ | |
404 | dictReplace(zs->dict,ele,score); | |
405 | server.dirty++; | |
406 | } else { | |
407 | zfree(score); | |
408 | } | |
409 | if (doincrement) | |
410 | addReplyDouble(c,*score); | |
411 | else | |
412 | addReply(c,shared.czero); | |
413 | } | |
414 | } | |
415 | ||
416 | void zaddCommand(redisClient *c) { | |
417 | double scoreval; | |
418 | ||
419 | if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return; | |
420 | zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0); | |
421 | } | |
422 | ||
423 | void zincrbyCommand(redisClient *c) { | |
424 | double scoreval; | |
425 | ||
426 | if (getDoubleFromObjectOrReply(c, c->argv[2], &scoreval, NULL) != REDIS_OK) return; | |
427 | zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1); | |
428 | } | |
429 | ||
430 | void zremCommand(redisClient *c) { | |
431 | robj *zsetobj; | |
432 | zset *zs; | |
433 | dictEntry *de; | |
434 | double *oldscore; | |
435 | int deleted; | |
436 | ||
437 | if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || | |
438 | checkType(c,zsetobj,REDIS_ZSET)) return; | |
439 | ||
440 | zs = zsetobj->ptr; | |
441 | de = dictFind(zs->dict,c->argv[2]); | |
442 | if (de == NULL) { | |
443 | addReply(c,shared.czero); | |
444 | return; | |
445 | } | |
446 | /* Delete from the skiplist */ | |
447 | oldscore = dictGetEntryVal(de); | |
448 | deleted = zslDelete(zs->zsl,*oldscore,c->argv[2]); | |
449 | redisAssert(deleted != 0); | |
450 | ||
451 | /* Delete from the hash table */ | |
452 | dictDelete(zs->dict,c->argv[2]); | |
453 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); | |
454 | if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]); | |
455 | server.dirty++; | |
456 | addReply(c,shared.cone); | |
457 | } | |
458 | ||
459 | void zremrangebyscoreCommand(redisClient *c) { | |
460 | double min; | |
461 | double max; | |
462 | long deleted; | |
463 | robj *zsetobj; | |
464 | zset *zs; | |
465 | ||
466 | if ((getDoubleFromObjectOrReply(c, c->argv[2], &min, NULL) != REDIS_OK) || | |
467 | (getDoubleFromObjectOrReply(c, c->argv[3], &max, NULL) != REDIS_OK)) return; | |
468 | ||
469 | if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || | |
470 | checkType(c,zsetobj,REDIS_ZSET)) return; | |
471 | ||
472 | zs = zsetobj->ptr; | |
473 | deleted = zslDeleteRangeByScore(zs->zsl,min,max,zs->dict); | |
474 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); | |
475 | if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]); | |
476 | server.dirty += deleted; | |
477 | addReplyLongLong(c,deleted); | |
478 | } | |
479 | ||
480 | void zremrangebyrankCommand(redisClient *c) { | |
481 | long start; | |
482 | long end; | |
483 | int llen; | |
484 | long deleted; | |
485 | robj *zsetobj; | |
486 | zset *zs; | |
487 | ||
488 | if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) || | |
489 | (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return; | |
490 | ||
491 | if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || | |
492 | checkType(c,zsetobj,REDIS_ZSET)) return; | |
493 | zs = zsetobj->ptr; | |
494 | llen = zs->zsl->length; | |
495 | ||
496 | /* convert negative indexes */ | |
497 | if (start < 0) start = llen+start; | |
498 | if (end < 0) end = llen+end; | |
499 | if (start < 0) start = 0; | |
500 | if (end < 0) end = 0; | |
501 | ||
502 | /* indexes sanity checks */ | |
503 | if (start > end || start >= llen) { | |
504 | addReply(c,shared.czero); | |
505 | return; | |
506 | } | |
507 | if (end >= llen) end = llen-1; | |
508 | ||
509 | /* increment start and end because zsl*Rank functions | |
510 | * use 1-based rank */ | |
511 | deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict); | |
512 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); | |
513 | if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]); | |
514 | server.dirty += deleted; | |
515 | addReplyLongLong(c, deleted); | |
516 | } | |
517 | ||
518 | typedef struct { | |
519 | dict *dict; | |
520 | double weight; | |
521 | } zsetopsrc; | |
522 | ||
523 | int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) { | |
524 | zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2; | |
525 | unsigned long size1, size2; | |
526 | size1 = d1->dict ? dictSize(d1->dict) : 0; | |
527 | size2 = d2->dict ? dictSize(d2->dict) : 0; | |
528 | return size1 - size2; | |
529 | } | |
530 | ||
531 | #define REDIS_AGGR_SUM 1 | |
532 | #define REDIS_AGGR_MIN 2 | |
533 | #define REDIS_AGGR_MAX 3 | |
534 | #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e)) | |
535 | ||
536 | inline static void zunionInterAggregate(double *target, double val, int aggregate) { | |
537 | if (aggregate == REDIS_AGGR_SUM) { | |
538 | *target = *target + val; | |
539 | } else if (aggregate == REDIS_AGGR_MIN) { | |
540 | *target = val < *target ? val : *target; | |
541 | } else if (aggregate == REDIS_AGGR_MAX) { | |
542 | *target = val > *target ? val : *target; | |
543 | } else { | |
544 | /* safety net */ | |
545 | redisPanic("Unknown ZUNION/INTER aggregate type"); | |
546 | } | |
547 | } | |
548 | ||
549 | void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) { | |
550 | int i, j, setnum; | |
551 | int aggregate = REDIS_AGGR_SUM; | |
552 | zsetopsrc *src; | |
553 | robj *dstobj; | |
554 | zset *dstzset; | |
555 | dictIterator *di; | |
556 | dictEntry *de; | |
557 | ||
558 | /* expect setnum input keys to be given */ | |
559 | setnum = atoi(c->argv[2]->ptr); | |
560 | if (setnum < 1) { | |
561 | addReplySds(c,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n")); | |
562 | return; | |
563 | } | |
564 | ||
565 | /* test if the expected number of keys would overflow */ | |
566 | if (3+setnum > c->argc) { | |
567 | addReply(c,shared.syntaxerr); | |
568 | return; | |
569 | } | |
570 | ||
571 | /* read keys to be used for input */ | |
572 | src = zmalloc(sizeof(zsetopsrc) * setnum); | |
573 | for (i = 0, j = 3; i < setnum; i++, j++) { | |
574 | robj *obj = lookupKeyWrite(c->db,c->argv[j]); | |
575 | if (!obj) { | |
576 | src[i].dict = NULL; | |
577 | } else { | |
578 | if (obj->type == REDIS_ZSET) { | |
579 | src[i].dict = ((zset*)obj->ptr)->dict; | |
580 | } else if (obj->type == REDIS_SET) { | |
581 | src[i].dict = (obj->ptr); | |
582 | } else { | |
583 | zfree(src); | |
584 | addReply(c,shared.wrongtypeerr); | |
585 | return; | |
586 | } | |
587 | } | |
588 | ||
589 | /* default all weights to 1 */ | |
590 | src[i].weight = 1.0; | |
591 | } | |
592 | ||
593 | /* parse optional extra arguments */ | |
594 | if (j < c->argc) { | |
595 | int remaining = c->argc - j; | |
596 | ||
597 | while (remaining) { | |
598 | if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) { | |
599 | j++; remaining--; | |
600 | for (i = 0; i < setnum; i++, j++, remaining--) { | |
601 | if (getDoubleFromObjectOrReply(c, c->argv[j], &src[i].weight, NULL) != REDIS_OK) | |
602 | return; | |
603 | } | |
604 | } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) { | |
605 | j++; remaining--; | |
606 | if (!strcasecmp(c->argv[j]->ptr,"sum")) { | |
607 | aggregate = REDIS_AGGR_SUM; | |
608 | } else if (!strcasecmp(c->argv[j]->ptr,"min")) { | |
609 | aggregate = REDIS_AGGR_MIN; | |
610 | } else if (!strcasecmp(c->argv[j]->ptr,"max")) { | |
611 | aggregate = REDIS_AGGR_MAX; | |
612 | } else { | |
613 | zfree(src); | |
614 | addReply(c,shared.syntaxerr); | |
615 | return; | |
616 | } | |
617 | j++; remaining--; | |
618 | } else { | |
619 | zfree(src); | |
620 | addReply(c,shared.syntaxerr); | |
621 | return; | |
622 | } | |
623 | } | |
624 | } | |
625 | ||
626 | /* sort sets from the smallest to largest, this will improve our | |
627 | * algorithm's performance */ | |
628 | qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality); | |
629 | ||
630 | dstobj = createZsetObject(); | |
631 | dstzset = dstobj->ptr; | |
632 | ||
633 | if (op == REDIS_OP_INTER) { | |
634 | /* skip going over all entries if the smallest zset is NULL or empty */ | |
635 | if (src[0].dict && dictSize(src[0].dict) > 0) { | |
636 | /* precondition: as src[0].dict is non-empty and the zsets are ordered | |
637 | * from small to large, all src[i > 0].dict are non-empty too */ | |
638 | di = dictGetIterator(src[0].dict); | |
639 | while((de = dictNext(di)) != NULL) { | |
640 | double *score = zmalloc(sizeof(double)), value; | |
641 | *score = src[0].weight * zunionInterDictValue(de); | |
642 | ||
643 | for (j = 1; j < setnum; j++) { | |
644 | dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de)); | |
645 | if (other) { | |
646 | value = src[j].weight * zunionInterDictValue(other); | |
647 | zunionInterAggregate(score, value, aggregate); | |
648 | } else { | |
649 | break; | |
650 | } | |
651 | } | |
652 | ||
653 | /* skip entry when not present in every source dict */ | |
654 | if (j != setnum) { | |
655 | zfree(score); | |
656 | } else { | |
657 | robj *o = dictGetEntryKey(de); | |
658 | dictAdd(dstzset->dict,o,score); | |
659 | incrRefCount(o); /* added to dictionary */ | |
660 | zslInsert(dstzset->zsl,*score,o); | |
661 | incrRefCount(o); /* added to skiplist */ | |
662 | } | |
663 | } | |
664 | dictReleaseIterator(di); | |
665 | } | |
666 | } else if (op == REDIS_OP_UNION) { | |
667 | for (i = 0; i < setnum; i++) { | |
668 | if (!src[i].dict) continue; | |
669 | ||
670 | di = dictGetIterator(src[i].dict); | |
671 | while((de = dictNext(di)) != NULL) { | |
672 | /* skip key when already processed */ | |
673 | if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) continue; | |
674 | ||
675 | double *score = zmalloc(sizeof(double)), value; | |
676 | *score = src[i].weight * zunionInterDictValue(de); | |
677 | ||
678 | /* because the zsets are sorted by size, its only possible | |
679 | * for sets at larger indices to hold this entry */ | |
680 | for (j = (i+1); j < setnum; j++) { | |
681 | dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de)); | |
682 | if (other) { | |
683 | value = src[j].weight * zunionInterDictValue(other); | |
684 | zunionInterAggregate(score, value, aggregate); | |
685 | } | |
686 | } | |
687 | ||
688 | robj *o = dictGetEntryKey(de); | |
689 | dictAdd(dstzset->dict,o,score); | |
690 | incrRefCount(o); /* added to dictionary */ | |
691 | zslInsert(dstzset->zsl,*score,o); | |
692 | incrRefCount(o); /* added to skiplist */ | |
693 | } | |
694 | dictReleaseIterator(di); | |
695 | } | |
696 | } else { | |
697 | /* unknown operator */ | |
698 | redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION); | |
699 | } | |
700 | ||
701 | dbDelete(c->db,dstkey); | |
702 | if (dstzset->zsl->length) { | |
703 | dbAdd(c->db,dstkey,dstobj); | |
704 | addReplyLongLong(c, dstzset->zsl->length); | |
705 | server.dirty++; | |
706 | } else { | |
707 | decrRefCount(dstobj); | |
708 | addReply(c, shared.czero); | |
709 | } | |
710 | zfree(src); | |
711 | } | |
712 | ||
713 | void zunionstoreCommand(redisClient *c) { | |
714 | zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION); | |
715 | } | |
716 | ||
717 | void zinterstoreCommand(redisClient *c) { | |
718 | zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER); | |
719 | } | |
720 | ||
721 | void zrangeGenericCommand(redisClient *c, int reverse) { | |
722 | robj *o; | |
723 | long start; | |
724 | long end; | |
725 | int withscores = 0; | |
726 | int llen; | |
727 | int rangelen, j; | |
728 | zset *zsetobj; | |
729 | zskiplist *zsl; | |
730 | zskiplistNode *ln; | |
731 | robj *ele; | |
732 | ||
733 | if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) || | |
734 | (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return; | |
735 | ||
736 | if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) { | |
737 | withscores = 1; | |
738 | } else if (c->argc >= 5) { | |
739 | addReply(c,shared.syntaxerr); | |
740 | return; | |
741 | } | |
742 | ||
743 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL | |
744 | || checkType(c,o,REDIS_ZSET)) return; | |
745 | zsetobj = o->ptr; | |
746 | zsl = zsetobj->zsl; | |
747 | llen = zsl->length; | |
748 | ||
749 | /* convert negative indexes */ | |
750 | if (start < 0) start = llen+start; | |
751 | if (end < 0) end = llen+end; | |
752 | if (start < 0) start = 0; | |
753 | if (end < 0) end = 0; | |
754 | ||
755 | /* indexes sanity checks */ | |
756 | if (start > end || start >= llen) { | |
757 | /* Out of range start or start > end result in empty list */ | |
758 | addReply(c,shared.emptymultibulk); | |
759 | return; | |
760 | } | |
761 | if (end >= llen) end = llen-1; | |
762 | rangelen = (end-start)+1; | |
763 | ||
764 | /* check if starting point is trivial, before searching | |
765 | * the element in log(N) time */ | |
766 | if (reverse) { | |
767 | ln = start == 0 ? zsl->tail : zslistTypeGetElementByRank(zsl, llen-start); | |
768 | } else { | |
769 | ln = start == 0 ? | |
770 | zsl->header->forward[0] : zslistTypeGetElementByRank(zsl, start+1); | |
771 | } | |
772 | ||
773 | /* Return the result in form of a multi-bulk reply */ | |
774 | addReplySds(c,sdscatprintf(sdsempty(),"*%d\r\n", | |
775 | withscores ? (rangelen*2) : rangelen)); | |
776 | for (j = 0; j < rangelen; j++) { | |
777 | ele = ln->obj; | |
778 | addReplyBulk(c,ele); | |
779 | if (withscores) | |
780 | addReplyDouble(c,ln->score); | |
781 | ln = reverse ? ln->backward : ln->forward[0]; | |
782 | } | |
783 | } | |
784 | ||
785 | void zrangeCommand(redisClient *c) { | |
786 | zrangeGenericCommand(c,0); | |
787 | } | |
788 | ||
789 | void zrevrangeCommand(redisClient *c) { | |
790 | zrangeGenericCommand(c,1); | |
791 | } | |
792 | ||
793 | /* This command implements both ZRANGEBYSCORE and ZCOUNT. | |
794 | * If justcount is non-zero, just the count is returned. */ | |
795 | void genericZrangebyscoreCommand(redisClient *c, int justcount) { | |
796 | robj *o; | |
797 | double min, max; | |
798 | int minex = 0, maxex = 0; /* are min or max exclusive? */ | |
799 | int offset = 0, limit = -1; | |
800 | int withscores = 0; | |
801 | int badsyntax = 0; | |
802 | ||
803 | /* Parse the min-max interval. If one of the values is prefixed | |
804 | * by the "(" character, it's considered "open". For instance | |
805 | * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max | |
806 | * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */ | |
807 | if (((char*)c->argv[2]->ptr)[0] == '(') { | |
808 | min = strtod((char*)c->argv[2]->ptr+1,NULL); | |
809 | minex = 1; | |
810 | } else { | |
811 | min = strtod(c->argv[2]->ptr,NULL); | |
812 | } | |
813 | if (((char*)c->argv[3]->ptr)[0] == '(') { | |
814 | max = strtod((char*)c->argv[3]->ptr+1,NULL); | |
815 | maxex = 1; | |
816 | } else { | |
817 | max = strtod(c->argv[3]->ptr,NULL); | |
818 | } | |
819 | ||
820 | /* Parse "WITHSCORES": note that if the command was called with | |
821 | * the name ZCOUNT then we are sure that c->argc == 4, so we'll never | |
822 | * enter the following paths to parse WITHSCORES and LIMIT. */ | |
823 | if (c->argc == 5 || c->argc == 8) { | |
824 | if (strcasecmp(c->argv[c->argc-1]->ptr,"withscores") == 0) | |
825 | withscores = 1; | |
826 | else | |
827 | badsyntax = 1; | |
828 | } | |
829 | if (c->argc != (4 + withscores) && c->argc != (7 + withscores)) | |
830 | badsyntax = 1; | |
831 | if (badsyntax) { | |
832 | addReplySds(c, | |
833 | sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n")); | |
834 | return; | |
835 | } | |
836 | ||
837 | /* Parse "LIMIT" */ | |
838 | if (c->argc == (7 + withscores) && strcasecmp(c->argv[4]->ptr,"limit")) { | |
839 | addReply(c,shared.syntaxerr); | |
840 | return; | |
841 | } else if (c->argc == (7 + withscores)) { | |
842 | offset = atoi(c->argv[5]->ptr); | |
843 | limit = atoi(c->argv[6]->ptr); | |
844 | if (offset < 0) offset = 0; | |
845 | } | |
846 | ||
847 | /* Ok, lookup the key and get the range */ | |
848 | o = lookupKeyRead(c->db,c->argv[1]); | |
849 | if (o == NULL) { | |
850 | addReply(c,justcount ? shared.czero : shared.emptymultibulk); | |
851 | } else { | |
852 | if (o->type != REDIS_ZSET) { | |
853 | addReply(c,shared.wrongtypeerr); | |
854 | } else { | |
855 | zset *zsetobj = o->ptr; | |
856 | zskiplist *zsl = zsetobj->zsl; | |
857 | zskiplistNode *ln; | |
858 | robj *ele, *lenobj = NULL; | |
859 | unsigned long rangelen = 0; | |
860 | ||
861 | /* Get the first node with the score >= min, or with | |
862 | * score > min if 'minex' is true. */ | |
863 | ln = zslFirstWithScore(zsl,min); | |
864 | while (minex && ln && ln->score == min) ln = ln->forward[0]; | |
865 | ||
866 | if (ln == NULL) { | |
867 | /* No element matching the speciifed interval */ | |
868 | addReply(c,justcount ? shared.czero : shared.emptymultibulk); | |
869 | return; | |
870 | } | |
871 | ||
872 | /* We don't know in advance how many matching elements there | |
873 | * are in the list, so we push this object that will represent | |
874 | * the multi-bulk length in the output buffer, and will "fix" | |
875 | * it later */ | |
876 | if (!justcount) { | |
877 | lenobj = createObject(REDIS_STRING,NULL); | |
878 | addReply(c,lenobj); | |
879 | decrRefCount(lenobj); | |
880 | } | |
881 | ||
882 | while(ln && (maxex ? (ln->score < max) : (ln->score <= max))) { | |
883 | if (offset) { | |
884 | offset--; | |
885 | ln = ln->forward[0]; | |
886 | continue; | |
887 | } | |
888 | if (limit == 0) break; | |
889 | if (!justcount) { | |
890 | ele = ln->obj; | |
891 | addReplyBulk(c,ele); | |
892 | if (withscores) | |
893 | addReplyDouble(c,ln->score); | |
894 | } | |
895 | ln = ln->forward[0]; | |
896 | rangelen++; | |
897 | if (limit > 0) limit--; | |
898 | } | |
899 | if (justcount) { | |
900 | addReplyLongLong(c,(long)rangelen); | |
901 | } else { | |
902 | lenobj->ptr = sdscatprintf(sdsempty(),"*%lu\r\n", | |
903 | withscores ? (rangelen*2) : rangelen); | |
904 | } | |
905 | } | |
906 | } | |
907 | } | |
908 | ||
909 | void zrangebyscoreCommand(redisClient *c) { | |
910 | genericZrangebyscoreCommand(c,0); | |
911 | } | |
912 | ||
913 | void zcountCommand(redisClient *c) { | |
914 | genericZrangebyscoreCommand(c,1); | |
915 | } | |
916 | ||
917 | void zcardCommand(redisClient *c) { | |
918 | robj *o; | |
919 | zset *zs; | |
920 | ||
921 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || | |
922 | checkType(c,o,REDIS_ZSET)) return; | |
923 | ||
924 | zs = o->ptr; | |
925 | addReplyUlong(c,zs->zsl->length); | |
926 | } | |
927 | ||
928 | void zscoreCommand(redisClient *c) { | |
929 | robj *o; | |
930 | zset *zs; | |
931 | dictEntry *de; | |
932 | ||
933 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL || | |
934 | checkType(c,o,REDIS_ZSET)) return; | |
935 | ||
936 | zs = o->ptr; | |
937 | de = dictFind(zs->dict,c->argv[2]); | |
938 | if (!de) { | |
939 | addReply(c,shared.nullbulk); | |
940 | } else { | |
941 | double *score = dictGetEntryVal(de); | |
942 | ||
943 | addReplyDouble(c,*score); | |
944 | } | |
945 | } | |
946 | ||
947 | void zrankGenericCommand(redisClient *c, int reverse) { | |
948 | robj *o; | |
949 | zset *zs; | |
950 | zskiplist *zsl; | |
951 | dictEntry *de; | |
952 | unsigned long rank; | |
953 | double *score; | |
954 | ||
955 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL || | |
956 | checkType(c,o,REDIS_ZSET)) return; | |
957 | ||
958 | zs = o->ptr; | |
959 | zsl = zs->zsl; | |
960 | de = dictFind(zs->dict,c->argv[2]); | |
961 | if (!de) { | |
962 | addReply(c,shared.nullbulk); | |
963 | return; | |
964 | } | |
965 | ||
966 | score = dictGetEntryVal(de); | |
967 | rank = zslistTypeGetRank(zsl, *score, c->argv[2]); | |
968 | if (rank) { | |
969 | if (reverse) { | |
970 | addReplyLongLong(c, zsl->length - rank); | |
971 | } else { | |
972 | addReplyLongLong(c, rank-1); | |
973 | } | |
974 | } else { | |
975 | addReply(c,shared.nullbulk); | |
976 | } | |
977 | } | |
978 | ||
979 | void zrankCommand(redisClient *c) { | |
980 | zrankGenericCommand(c, 0); | |
981 | } | |
982 | ||
983 | void zrevrankCommand(redisClient *c) { | |
984 | zrankGenericCommand(c, 1); | |
985 | } |