]>
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) { | |
2159782b | 27 | zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel)); |
e2641e09 | 28 | zn->score = score; |
29 | zn->obj = obj; | |
30 | return zn; | |
31 | } | |
32 | ||
33 | zskiplist *zslCreate(void) { | |
34 | int j; | |
35 | zskiplist *zsl; | |
36 | ||
37 | zsl = zmalloc(sizeof(*zsl)); | |
38 | zsl->level = 1; | |
39 | zsl->length = 0; | |
40 | zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL); | |
41 | for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) { | |
2159782b PN |
42 | zsl->header->level[j].forward = NULL; |
43 | zsl->header->level[j].span = 0; | |
e2641e09 | 44 | } |
45 | zsl->header->backward = NULL; | |
46 | zsl->tail = NULL; | |
47 | return zsl; | |
48 | } | |
49 | ||
50 | void zslFreeNode(zskiplistNode *node) { | |
51 | decrRefCount(node->obj); | |
e2641e09 | 52 | zfree(node); |
53 | } | |
54 | ||
55 | void zslFree(zskiplist *zsl) { | |
2159782b | 56 | zskiplistNode *node = zsl->header->level[0].forward, *next; |
e2641e09 | 57 | |
e2641e09 | 58 | zfree(zsl->header); |
59 | while(node) { | |
2159782b | 60 | next = node->level[0].forward; |
e2641e09 | 61 | zslFreeNode(node); |
62 | node = next; | |
63 | } | |
64 | zfree(zsl); | |
65 | } | |
66 | ||
67 | int zslRandomLevel(void) { | |
68 | int level = 1; | |
69 | while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF)) | |
70 | level += 1; | |
71 | return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL; | |
72 | } | |
73 | ||
69ef89f2 | 74 | zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) { |
e2641e09 | 75 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; |
76 | unsigned int rank[ZSKIPLIST_MAXLEVEL]; | |
77 | int i, level; | |
78 | ||
79 | x = zsl->header; | |
80 | for (i = zsl->level-1; i >= 0; i--) { | |
81 | /* store rank that is crossed to reach the insert position */ | |
82 | rank[i] = i == (zsl->level-1) ? 0 : rank[i+1]; | |
2159782b PN |
83 | while (x->level[i].forward && |
84 | (x->level[i].forward->score < score || | |
85 | (x->level[i].forward->score == score && | |
86 | compareStringObjects(x->level[i].forward->obj,obj) < 0))) { | |
87 | rank[i] += x->level[i].span; | |
88 | x = x->level[i].forward; | |
e2641e09 | 89 | } |
90 | update[i] = x; | |
91 | } | |
92 | /* we assume the key is not already inside, since we allow duplicated | |
93 | * scores, and the re-insertion of score and redis object should never | |
94 | * happpen since the caller of zslInsert() should test in the hash table | |
95 | * if the element is already inside or not. */ | |
96 | level = zslRandomLevel(); | |
97 | if (level > zsl->level) { | |
98 | for (i = zsl->level; i < level; i++) { | |
99 | rank[i] = 0; | |
100 | update[i] = zsl->header; | |
2159782b | 101 | update[i]->level[i].span = zsl->length; |
e2641e09 | 102 | } |
103 | zsl->level = level; | |
104 | } | |
105 | x = zslCreateNode(level,score,obj); | |
106 | for (i = 0; i < level; i++) { | |
2159782b PN |
107 | x->level[i].forward = update[i]->level[i].forward; |
108 | update[i]->level[i].forward = x; | |
e2641e09 | 109 | |
110 | /* update span covered by update[i] as x is inserted here */ | |
2159782b PN |
111 | x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]); |
112 | update[i]->level[i].span = (rank[0] - rank[i]) + 1; | |
e2641e09 | 113 | } |
114 | ||
115 | /* increment span for untouched levels */ | |
116 | for (i = level; i < zsl->level; i++) { | |
2159782b | 117 | update[i]->level[i].span++; |
e2641e09 | 118 | } |
119 | ||
120 | x->backward = (update[0] == zsl->header) ? NULL : update[0]; | |
2159782b PN |
121 | if (x->level[0].forward) |
122 | x->level[0].forward->backward = x; | |
e2641e09 | 123 | else |
124 | zsl->tail = x; | |
125 | zsl->length++; | |
69ef89f2 | 126 | return x; |
e2641e09 | 127 | } |
128 | ||
129 | /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */ | |
130 | void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) { | |
131 | int i; | |
132 | for (i = 0; i < zsl->level; i++) { | |
2159782b PN |
133 | if (update[i]->level[i].forward == x) { |
134 | update[i]->level[i].span += x->level[i].span - 1; | |
135 | update[i]->level[i].forward = x->level[i].forward; | |
e2641e09 | 136 | } else { |
2159782b | 137 | update[i]->level[i].span -= 1; |
e2641e09 | 138 | } |
139 | } | |
2159782b PN |
140 | if (x->level[0].forward) { |
141 | x->level[0].forward->backward = x->backward; | |
e2641e09 | 142 | } else { |
143 | zsl->tail = x->backward; | |
144 | } | |
2159782b | 145 | while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL) |
e2641e09 | 146 | zsl->level--; |
147 | zsl->length--; | |
148 | } | |
149 | ||
150 | /* Delete an element with matching score/object from the skiplist. */ | |
151 | int zslDelete(zskiplist *zsl, double score, robj *obj) { | |
152 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
153 | int i; | |
154 | ||
155 | x = zsl->header; | |
156 | for (i = zsl->level-1; i >= 0; i--) { | |
2159782b PN |
157 | while (x->level[i].forward && |
158 | (x->level[i].forward->score < score || | |
159 | (x->level[i].forward->score == score && | |
160 | compareStringObjects(x->level[i].forward->obj,obj) < 0))) | |
161 | x = x->level[i].forward; | |
e2641e09 | 162 | update[i] = x; |
163 | } | |
164 | /* We may have multiple elements with the same score, what we need | |
165 | * is to find the element with both the right score and object. */ | |
2159782b | 166 | x = x->level[0].forward; |
e2641e09 | 167 | if (x && score == x->score && equalStringObjects(x->obj,obj)) { |
168 | zslDeleteNode(zsl, x, update); | |
169 | zslFreeNode(x); | |
170 | return 1; | |
171 | } else { | |
172 | return 0; /* not found */ | |
173 | } | |
174 | return 0; /* not found */ | |
175 | } | |
176 | ||
91504b6c PN |
177 | /* Struct to hold a inclusive/exclusive range spec. */ |
178 | typedef struct { | |
179 | double min, max; | |
180 | int minex, maxex; /* are min or max exclusive? */ | |
181 | } zrangespec; | |
182 | ||
45290ad9 | 183 | static int zslValueGteMin(double value, zrangespec *spec) { |
22b9bf15 PN |
184 | return spec->minex ? (value > spec->min) : (value >= spec->min); |
185 | } | |
186 | ||
45290ad9 | 187 | static int zslValueLteMax(double value, zrangespec *spec) { |
22b9bf15 PN |
188 | return spec->maxex ? (value < spec->max) : (value <= spec->max); |
189 | } | |
190 | ||
df278b8b | 191 | static int zslValueInRange(double value, zrangespec *spec) { |
45290ad9 | 192 | return zslValueGteMin(value,spec) && zslValueLteMax(value,spec); |
22b9bf15 PN |
193 | } |
194 | ||
195 | /* Returns if there is a part of the zset is in range. */ | |
196 | int zslIsInRange(zskiplist *zsl, zrangespec *range) { | |
197 | zskiplistNode *x; | |
198 | ||
8e1b3277 PN |
199 | /* Test for ranges that will always be empty. */ |
200 | if (range->min > range->max || | |
201 | (range->min == range->max && (range->minex || range->maxex))) | |
202 | return 0; | |
22b9bf15 | 203 | x = zsl->tail; |
45290ad9 | 204 | if (x == NULL || !zslValueGteMin(x->score,range)) |
22b9bf15 PN |
205 | return 0; |
206 | x = zsl->header->level[0].forward; | |
45290ad9 | 207 | if (x == NULL || !zslValueLteMax(x->score,range)) |
22b9bf15 PN |
208 | return 0; |
209 | return 1; | |
210 | } | |
211 | ||
212 | /* Find the first node that is contained in the specified range. | |
213 | * Returns NULL when no element is contained in the range. */ | |
214 | zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec range) { | |
215 | zskiplistNode *x; | |
216 | int i; | |
217 | ||
218 | /* If everything is out of range, return early. */ | |
219 | if (!zslIsInRange(zsl,&range)) return NULL; | |
220 | ||
221 | x = zsl->header; | |
222 | for (i = zsl->level-1; i >= 0; i--) { | |
223 | /* Go forward while *OUT* of range. */ | |
224 | while (x->level[i].forward && | |
45290ad9 | 225 | !zslValueGteMin(x->level[i].forward->score,&range)) |
22b9bf15 PN |
226 | x = x->level[i].forward; |
227 | } | |
228 | ||
229 | /* The tail is in range, so the previous block should always return a | |
230 | * node that is non-NULL and the last one to be out of range. */ | |
231 | x = x->level[0].forward; | |
232 | redisAssert(x != NULL && zslValueInRange(x->score,&range)); | |
233 | return x; | |
234 | } | |
235 | ||
236 | /* Find the last node that is contained in the specified range. | |
237 | * Returns NULL when no element is contained in the range. */ | |
238 | zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec range) { | |
239 | zskiplistNode *x; | |
240 | int i; | |
241 | ||
242 | /* If everything is out of range, return early. */ | |
243 | if (!zslIsInRange(zsl,&range)) return NULL; | |
244 | ||
245 | x = zsl->header; | |
246 | for (i = zsl->level-1; i >= 0; i--) { | |
247 | /* Go forward while *IN* range. */ | |
248 | while (x->level[i].forward && | |
45290ad9 | 249 | zslValueLteMax(x->level[i].forward->score,&range)) |
22b9bf15 PN |
250 | x = x->level[i].forward; |
251 | } | |
252 | ||
253 | /* The header is in range, so the previous block should always return a | |
254 | * node that is non-NULL and in range. */ | |
255 | redisAssert(x != NULL && zslValueInRange(x->score,&range)); | |
256 | return x; | |
257 | } | |
258 | ||
e2641e09 | 259 | /* Delete all the elements with score between min and max from the skiplist. |
260 | * Min and mx are inclusive, so a score >= min || score <= max is deleted. | |
261 | * Note that this function takes the reference to the hash table view of the | |
262 | * sorted set, in order to remove the elements from the hash table too. */ | |
91504b6c | 263 | unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec range, dict *dict) { |
e2641e09 | 264 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; |
265 | unsigned long removed = 0; | |
266 | int i; | |
267 | ||
268 | x = zsl->header; | |
269 | for (i = zsl->level-1; i >= 0; i--) { | |
91504b6c PN |
270 | while (x->level[i].forward && (range.minex ? |
271 | x->level[i].forward->score <= range.min : | |
272 | x->level[i].forward->score < range.min)) | |
273 | x = x->level[i].forward; | |
e2641e09 | 274 | update[i] = x; |
275 | } | |
91504b6c PN |
276 | |
277 | /* Current node is the last with score < or <= min. */ | |
2159782b | 278 | x = x->level[0].forward; |
91504b6c PN |
279 | |
280 | /* Delete nodes while in range. */ | |
281 | while (x && (range.maxex ? x->score < range.max : x->score <= range.max)) { | |
2159782b | 282 | zskiplistNode *next = x->level[0].forward; |
69ef89f2 | 283 | zslDeleteNode(zsl,x,update); |
e2641e09 | 284 | dictDelete(dict,x->obj); |
285 | zslFreeNode(x); | |
286 | removed++; | |
287 | x = next; | |
288 | } | |
91504b6c | 289 | return removed; |
e2641e09 | 290 | } |
291 | ||
292 | /* Delete all the elements with rank between start and end from the skiplist. | |
293 | * Start and end are inclusive. Note that start and end need to be 1-based */ | |
294 | unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) { | |
295 | zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; | |
296 | unsigned long traversed = 0, removed = 0; | |
297 | int i; | |
298 | ||
299 | x = zsl->header; | |
300 | for (i = zsl->level-1; i >= 0; i--) { | |
2159782b PN |
301 | while (x->level[i].forward && (traversed + x->level[i].span) < start) { |
302 | traversed += x->level[i].span; | |
303 | x = x->level[i].forward; | |
e2641e09 | 304 | } |
305 | update[i] = x; | |
306 | } | |
307 | ||
308 | traversed++; | |
2159782b | 309 | x = x->level[0].forward; |
e2641e09 | 310 | while (x && traversed <= end) { |
2159782b | 311 | zskiplistNode *next = x->level[0].forward; |
69ef89f2 | 312 | zslDeleteNode(zsl,x,update); |
e2641e09 | 313 | dictDelete(dict,x->obj); |
314 | zslFreeNode(x); | |
315 | removed++; | |
316 | traversed++; | |
317 | x = next; | |
318 | } | |
319 | return removed; | |
320 | } | |
321 | ||
e2641e09 | 322 | /* Find the rank for an element by both score and key. |
323 | * Returns 0 when the element cannot be found, rank otherwise. | |
324 | * Note that the rank is 1-based due to the span of zsl->header to the | |
325 | * first element. */ | |
a3004773 | 326 | unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) { |
e2641e09 | 327 | zskiplistNode *x; |
328 | unsigned long rank = 0; | |
329 | int i; | |
330 | ||
331 | x = zsl->header; | |
332 | for (i = zsl->level-1; i >= 0; i--) { | |
2159782b PN |
333 | while (x->level[i].forward && |
334 | (x->level[i].forward->score < score || | |
335 | (x->level[i].forward->score == score && | |
336 | compareStringObjects(x->level[i].forward->obj,o) <= 0))) { | |
337 | rank += x->level[i].span; | |
338 | x = x->level[i].forward; | |
e2641e09 | 339 | } |
340 | ||
341 | /* x might be equal to zsl->header, so test if obj is non-NULL */ | |
342 | if (x->obj && equalStringObjects(x->obj,o)) { | |
343 | return rank; | |
344 | } | |
345 | } | |
346 | return 0; | |
347 | } | |
348 | ||
349 | /* Finds an element by its rank. The rank argument needs to be 1-based. */ | |
a3004773 | 350 | zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) { |
e2641e09 | 351 | zskiplistNode *x; |
352 | unsigned long traversed = 0; | |
353 | int i; | |
354 | ||
355 | x = zsl->header; | |
356 | for (i = zsl->level-1; i >= 0; i--) { | |
2159782b | 357 | while (x->level[i].forward && (traversed + x->level[i].span) <= rank) |
e2641e09 | 358 | { |
2159782b PN |
359 | traversed += x->level[i].span; |
360 | x = x->level[i].forward; | |
e2641e09 | 361 | } |
362 | if (traversed == rank) { | |
363 | return x; | |
364 | } | |
365 | } | |
366 | return NULL; | |
367 | } | |
368 | ||
25bb8a44 | 369 | /* Populate the rangespec according to the objects min and max. */ |
7236fdb2 PN |
370 | static int zslParseRange(robj *min, robj *max, zrangespec *spec) { |
371 | char *eptr; | |
25bb8a44 PN |
372 | spec->minex = spec->maxex = 0; |
373 | ||
374 | /* Parse the min-max interval. If one of the values is prefixed | |
375 | * by the "(" character, it's considered "open". For instance | |
376 | * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max | |
377 | * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */ | |
378 | if (min->encoding == REDIS_ENCODING_INT) { | |
379 | spec->min = (long)min->ptr; | |
380 | } else { | |
381 | if (((char*)min->ptr)[0] == '(') { | |
7236fdb2 PN |
382 | spec->min = strtod((char*)min->ptr+1,&eptr); |
383 | if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR; | |
25bb8a44 PN |
384 | spec->minex = 1; |
385 | } else { | |
7236fdb2 PN |
386 | spec->min = strtod((char*)min->ptr,&eptr); |
387 | if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR; | |
25bb8a44 PN |
388 | } |
389 | } | |
390 | if (max->encoding == REDIS_ENCODING_INT) { | |
391 | spec->max = (long)max->ptr; | |
392 | } else { | |
393 | if (((char*)max->ptr)[0] == '(') { | |
7236fdb2 PN |
394 | spec->max = strtod((char*)max->ptr+1,&eptr); |
395 | if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR; | |
25bb8a44 PN |
396 | spec->maxex = 1; |
397 | } else { | |
7236fdb2 PN |
398 | spec->max = strtod((char*)max->ptr,&eptr); |
399 | if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR; | |
25bb8a44 PN |
400 | } |
401 | } | |
402 | ||
403 | return REDIS_OK; | |
404 | } | |
405 | ||
21c5b508 PN |
406 | /*----------------------------------------------------------------------------- |
407 | * Ziplist-backed sorted set API | |
408 | *----------------------------------------------------------------------------*/ | |
409 | ||
410 | double zzlGetScore(unsigned char *sptr) { | |
411 | unsigned char *vstr; | |
412 | unsigned int vlen; | |
413 | long long vlong; | |
414 | char buf[128]; | |
415 | double score; | |
416 | ||
417 | redisAssert(sptr != NULL); | |
418 | redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong)); | |
419 | ||
420 | if (vstr) { | |
421 | memcpy(buf,vstr,vlen); | |
422 | buf[vlen] = '\0'; | |
423 | score = strtod(buf,NULL); | |
424 | } else { | |
425 | score = vlong; | |
426 | } | |
427 | ||
428 | return score; | |
429 | } | |
430 | ||
431 | /* Compare element in sorted set with given element. */ | |
432 | int zzlCompareElements(unsigned char *eptr, unsigned char *cstr, unsigned int clen) { | |
433 | unsigned char *vstr; | |
434 | unsigned int vlen; | |
435 | long long vlong; | |
436 | unsigned char vbuf[32]; | |
437 | int minlen, cmp; | |
438 | ||
439 | redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong)); | |
440 | if (vstr == NULL) { | |
441 | /* Store string representation of long long in buf. */ | |
442 | vlen = ll2string((char*)vbuf,sizeof(vbuf),vlong); | |
443 | vstr = vbuf; | |
444 | } | |
445 | ||
446 | minlen = (vlen < clen) ? vlen : clen; | |
447 | cmp = memcmp(vstr,cstr,minlen); | |
448 | if (cmp == 0) return vlen-clen; | |
449 | return cmp; | |
450 | } | |
451 | ||
0b10e104 PN |
452 | unsigned int *zzlLength(robj *zobj) { |
453 | unsigned char *zl = zobj->ptr; | |
454 | return ziplistLen(zl)/2; | |
455 | } | |
456 | ||
21c5b508 PN |
457 | unsigned char *zzlFind(robj *zobj, robj *ele, double *score) { |
458 | unsigned char *zl = zobj->ptr; | |
459 | unsigned char *eptr = ziplistIndex(zl,0), *sptr; | |
460 | ||
461 | ele = getDecodedObject(ele); | |
462 | while (eptr != NULL) { | |
463 | sptr = ziplistNext(zl,eptr); | |
464 | redisAssert(sptr != NULL); | |
465 | ||
466 | if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) { | |
467 | /* Matching element, pull out score. */ | |
0b10e104 | 468 | if (score != NULL) *score = zzlGetScore(sptr); |
21c5b508 PN |
469 | decrRefCount(ele); |
470 | return eptr; | |
471 | } | |
472 | ||
473 | /* Move to next element. */ | |
474 | eptr = ziplistNext(zl,sptr); | |
475 | } | |
476 | ||
477 | decrRefCount(ele); | |
478 | return NULL; | |
479 | } | |
480 | ||
481 | /* Delete (element,score) pair from ziplist. Use local copy of eptr because we | |
482 | * don't want to modify the one given as argument. */ | |
483 | int zzlDelete(robj *zobj, unsigned char *eptr) { | |
484 | unsigned char *zl = zobj->ptr; | |
485 | unsigned char *p = eptr; | |
486 | ||
487 | /* TODO: add function to ziplist API to delete N elements from offset. */ | |
488 | zl = ziplistDelete(zl,&p); | |
489 | zl = ziplistDelete(zl,&p); | |
490 | zobj->ptr = zl; | |
491 | return REDIS_OK; | |
492 | } | |
493 | ||
494 | int zzlInsertAt(robj *zobj, robj *ele, double score, unsigned char *eptr) { | |
495 | unsigned char *zl = zobj->ptr; | |
496 | unsigned char *sptr; | |
497 | char scorebuf[128]; | |
498 | int scorelen; | |
499 | int offset; | |
500 | ||
501 | redisAssert(ele->encoding == REDIS_ENCODING_RAW); | |
502 | scorelen = d2string(scorebuf,sizeof(scorebuf),score); | |
503 | if (eptr == NULL) { | |
504 | zl = ziplistPush(zl,ele->ptr,sdslen(ele->ptr),ZIPLIST_TAIL); | |
505 | zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL); | |
506 | } else { | |
507 | /* Keep offset relative to zl, as it might be re-allocated. */ | |
508 | offset = eptr-zl; | |
509 | zl = ziplistInsert(zl,eptr,ele->ptr,sdslen(ele->ptr)); | |
510 | eptr = zl+offset; | |
511 | ||
512 | /* Insert score after the element. */ | |
513 | redisAssert((sptr = ziplistNext(zl,eptr)) != NULL); | |
514 | zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen); | |
515 | } | |
516 | ||
517 | zobj->ptr = zl; | |
518 | return REDIS_OK; | |
519 | } | |
520 | ||
521 | /* Insert (element,score) pair in ziplist. This function assumes the element is | |
522 | * not yet present in the list. */ | |
523 | int zzlInsert(robj *zobj, robj *ele, double score) { | |
524 | unsigned char *zl = zobj->ptr; | |
525 | unsigned char *eptr = ziplistIndex(zl,0), *sptr; | |
526 | double s; | |
21c5b508 PN |
527 | |
528 | ele = getDecodedObject(ele); | |
529 | while (eptr != NULL) { | |
530 | sptr = ziplistNext(zl,eptr); | |
531 | redisAssert(sptr != NULL); | |
532 | s = zzlGetScore(sptr); | |
533 | ||
534 | if (s > score) { | |
535 | /* First element with score larger than score for element to be | |
536 | * inserted. This means we should take its spot in the list to | |
537 | * maintain ordering. */ | |
21c5b508 PN |
538 | zzlInsertAt(zobj,ele,score,eptr); |
539 | break; | |
8218db3d PN |
540 | } else if (s == score) { |
541 | /* Ensure lexicographical ordering for elements. */ | |
542 | if (zzlCompareElements(eptr,ele->ptr,sdslen(ele->ptr)) < 0) { | |
543 | zzlInsertAt(zobj,ele,score,eptr); | |
544 | break; | |
545 | } | |
21c5b508 PN |
546 | } |
547 | ||
548 | /* Move to next element. */ | |
549 | eptr = ziplistNext(zl,sptr); | |
550 | } | |
551 | ||
552 | /* Push on tail of list when it was not yet inserted. */ | |
8218db3d PN |
553 | if (eptr == NULL) |
554 | zzlInsertAt(zobj,ele,score,NULL); | |
21c5b508 PN |
555 | |
556 | decrRefCount(ele); | |
557 | return REDIS_OK; | |
558 | } | |
25bb8a44 | 559 | |
e2641e09 | 560 | /*----------------------------------------------------------------------------- |
561 | * Sorted set commands | |
562 | *----------------------------------------------------------------------------*/ | |
563 | ||
69ef89f2 | 564 | /* This generic command implements both ZADD and ZINCRBY. */ |
3ca7532a | 565 | void zaddGenericCommand(redisClient *c, int incr) { |
21c5b508 | 566 | static char *nanerr = "resulting score is not a number (NaN)"; |
3ca7532a PN |
567 | robj *key = c->argv[1]; |
568 | robj *ele; | |
21c5b508 PN |
569 | robj *zobj; |
570 | robj *curobj; | |
3ca7532a PN |
571 | double score, curscore = 0.0; |
572 | ||
573 | if (getDoubleFromObjectOrReply(c,c->argv[2],&score,NULL) != REDIS_OK) | |
574 | return; | |
21c5b508 PN |
575 | |
576 | zobj = lookupKeyWrite(c->db,key); | |
577 | if (zobj == NULL) { | |
578 | zobj = createZsetZiplistObject(); | |
579 | dbAdd(c->db,key,zobj); | |
e2641e09 | 580 | } else { |
21c5b508 | 581 | if (zobj->type != REDIS_ZSET) { |
e2641e09 | 582 | addReply(c,shared.wrongtypeerr); |
583 | return; | |
584 | } | |
585 | } | |
e2641e09 | 586 | |
21c5b508 PN |
587 | if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { |
588 | unsigned char *eptr; | |
589 | ||
3ca7532a PN |
590 | /* Prefer non-encoded element when dealing with ziplists. */ |
591 | ele = c->argv[3]; | |
21c5b508 PN |
592 | if ((eptr = zzlFind(zobj,ele,&curscore)) != NULL) { |
593 | if (incr) { | |
594 | score += curscore; | |
595 | if (isnan(score)) { | |
596 | addReplyError(c,nanerr); | |
597 | /* Don't need to check if the sorted set is empty, because | |
598 | * we know it has at least one element. */ | |
599 | return; | |
600 | } | |
601 | } | |
602 | ||
603 | /* Remove and re-insert when score changed. */ | |
604 | if (score != curscore) { | |
605 | redisAssert(zzlDelete(zobj,eptr) == REDIS_OK); | |
606 | redisAssert(zzlInsert(zobj,ele,score) == REDIS_OK); | |
607 | ||
608 | signalModifiedKey(c->db,key); | |
609 | server.dirty++; | |
610 | } | |
611 | ||
612 | if (incr) /* ZINCRBY */ | |
613 | addReplyDouble(c,score); | |
614 | else /* ZADD */ | |
615 | addReply(c,shared.czero); | |
616 | } else { | |
617 | redisAssert(zzlInsert(zobj,ele,score) == REDIS_OK); | |
69ef89f2 | 618 | |
21c5b508 PN |
619 | signalModifiedKey(c->db,key); |
620 | server.dirty++; | |
69ef89f2 | 621 | |
21c5b508 PN |
622 | if (incr) /* ZINCRBY */ |
623 | addReplyDouble(c,score); | |
624 | else /* ZADD */ | |
625 | addReply(c,shared.cone); | |
626 | } | |
627 | } else if (zobj->encoding == REDIS_ENCODING_RAW) { | |
628 | zset *zs = zobj->ptr; | |
629 | zskiplistNode *znode; | |
e2641e09 | 630 | dictEntry *de; |
e2641e09 | 631 | |
3ca7532a | 632 | ele = c->argv[3] = tryObjectEncoding(c->argv[3]); |
e2641e09 | 633 | de = dictFind(zs->dict,ele); |
21c5b508 PN |
634 | if (de != NULL) { |
635 | curobj = dictGetEntryKey(de); | |
636 | curscore = *(double*)dictGetEntryVal(de); | |
637 | ||
638 | if (incr) { | |
639 | score += curscore; | |
640 | if (isnan(score)) { | |
641 | addReplyError(c,nanerr); | |
642 | /* Don't need to check if the sorted set is empty, because | |
643 | * we know it has at least one element. */ | |
644 | return; | |
645 | } | |
646 | } | |
647 | ||
648 | /* Remove and re-insert when score changed. We can safely delete | |
649 | * the key object from the skiplist, since the dictionary still has | |
650 | * a reference to it. */ | |
651 | if (score != curscore) { | |
652 | redisAssert(zslDelete(zs->zsl,curscore,curobj)); | |
653 | znode = zslInsert(zs->zsl,score,curobj); | |
654 | incrRefCount(curobj); /* Re-inserted in skiplist. */ | |
655 | dictGetEntryVal(de) = &znode->score; /* Update score ptr. */ | |
656 | ||
657 | signalModifiedKey(c->db,key); | |
658 | server.dirty++; | |
659 | } | |
660 | ||
661 | if (incr) /* ZINCRBY */ | |
662 | addReplyDouble(c,score); | |
663 | else /* ZADD */ | |
664 | addReply(c,shared.czero); | |
665 | } else { | |
666 | znode = zslInsert(zs->zsl,score,ele); | |
667 | incrRefCount(ele); /* Inserted in skiplist. */ | |
668 | redisAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK); | |
669 | incrRefCount(ele); /* Added to dictionary. */ | |
670 | ||
671 | signalModifiedKey(c->db,key); | |
e2641e09 | 672 | server.dirty++; |
21c5b508 PN |
673 | |
674 | if (incr) /* ZINCRBY */ | |
675 | addReplyDouble(c,score); | |
676 | else /* ZADD */ | |
677 | addReply(c,shared.cone); | |
e2641e09 | 678 | } |
21c5b508 PN |
679 | } else { |
680 | redisPanic("Unknown sorted set encoding"); | |
e2641e09 | 681 | } |
682 | } | |
683 | ||
684 | void zaddCommand(redisClient *c) { | |
3ca7532a | 685 | zaddGenericCommand(c,0); |
e2641e09 | 686 | } |
687 | ||
688 | void zincrbyCommand(redisClient *c) { | |
3ca7532a | 689 | zaddGenericCommand(c,1); |
e2641e09 | 690 | } |
691 | ||
692 | void zremCommand(redisClient *c) { | |
0b10e104 PN |
693 | robj *key = c->argv[1]; |
694 | robj *ele = c->argv[2]; | |
695 | robj *zobj; | |
696 | ||
697 | if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL || | |
698 | checkType(c,zobj,REDIS_ZSET)) return; | |
699 | ||
700 | if (zobj->encoding == REDIS_ENCODING_ZIPLIST) { | |
701 | unsigned char *eptr; | |
702 | ||
703 | if ((eptr = zzlFind(zobj,ele,NULL)) != NULL) { | |
704 | redisAssert(zzlDelete(zobj,eptr) == REDIS_OK); | |
705 | if (zzlLength(zobj) == 0) dbDelete(c->db,key); | |
706 | } else { | |
707 | addReply(c,shared.czero); | |
708 | return; | |
709 | } | |
710 | } else if (zobj->encoding == REDIS_ENCODING_RAW) { | |
711 | zset *zs = zobj->ptr; | |
712 | dictEntry *de; | |
713 | double score; | |
714 | ||
715 | de = dictFind(zs->dict,ele); | |
716 | if (de != NULL) { | |
717 | /* Delete from the skiplist */ | |
718 | score = *(double*)dictGetEntryVal(de); | |
719 | redisAssert(zslDelete(zs->zsl,score,ele)); | |
720 | ||
721 | /* Delete from the hash table */ | |
722 | dictDelete(zs->dict,ele); | |
723 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); | |
724 | if (dictSize(zs->dict) == 0) dbDelete(c->db,key); | |
725 | } else { | |
726 | addReply(c,shared.czero); | |
727 | return; | |
728 | } | |
729 | } else { | |
730 | redisPanic("Unknown sorted set encoding"); | |
e2641e09 | 731 | } |
e2641e09 | 732 | |
0b10e104 | 733 | signalModifiedKey(c->db,key); |
e2641e09 | 734 | server.dirty++; |
735 | addReply(c,shared.cone); | |
736 | } | |
737 | ||
738 | void zremrangebyscoreCommand(redisClient *c) { | |
91504b6c | 739 | zrangespec range; |
e2641e09 | 740 | long deleted; |
91504b6c | 741 | robj *o; |
e2641e09 | 742 | zset *zs; |
743 | ||
91504b6c | 744 | /* Parse the range arguments. */ |
7236fdb2 PN |
745 | if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) { |
746 | addReplyError(c,"min or max is not a double"); | |
747 | return; | |
748 | } | |
e2641e09 | 749 | |
91504b6c PN |
750 | if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || |
751 | checkType(c,o,REDIS_ZSET)) return; | |
e2641e09 | 752 | |
91504b6c PN |
753 | zs = o->ptr; |
754 | deleted = zslDeleteRangeByScore(zs->zsl,range,zs->dict); | |
e2641e09 | 755 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); |
756 | if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]); | |
cea8c5cd | 757 | if (deleted) signalModifiedKey(c->db,c->argv[1]); |
e2641e09 | 758 | server.dirty += deleted; |
759 | addReplyLongLong(c,deleted); | |
760 | } | |
761 | ||
762 | void zremrangebyrankCommand(redisClient *c) { | |
763 | long start; | |
764 | long end; | |
765 | int llen; | |
766 | long deleted; | |
767 | robj *zsetobj; | |
768 | zset *zs; | |
769 | ||
770 | if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) || | |
771 | (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return; | |
772 | ||
773 | if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL || | |
774 | checkType(c,zsetobj,REDIS_ZSET)) return; | |
775 | zs = zsetobj->ptr; | |
776 | llen = zs->zsl->length; | |
777 | ||
778 | /* convert negative indexes */ | |
779 | if (start < 0) start = llen+start; | |
780 | if (end < 0) end = llen+end; | |
781 | if (start < 0) start = 0; | |
e2641e09 | 782 | |
d0a4e24e PN |
783 | /* Invariant: start >= 0, so this test will be true when end < 0. |
784 | * The range is empty when start > end or start >= length. */ | |
e2641e09 | 785 | if (start > end || start >= llen) { |
786 | addReply(c,shared.czero); | |
787 | return; | |
788 | } | |
789 | if (end >= llen) end = llen-1; | |
790 | ||
791 | /* increment start and end because zsl*Rank functions | |
792 | * use 1-based rank */ | |
793 | deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict); | |
794 | if (htNeedsResize(zs->dict)) dictResize(zs->dict); | |
795 | if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]); | |
cea8c5cd | 796 | if (deleted) signalModifiedKey(c->db,c->argv[1]); |
e2641e09 | 797 | server.dirty += deleted; |
798 | addReplyLongLong(c, deleted); | |
799 | } | |
800 | ||
801 | typedef struct { | |
802 | dict *dict; | |
803 | double weight; | |
804 | } zsetopsrc; | |
805 | ||
806 | int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) { | |
807 | zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2; | |
808 | unsigned long size1, size2; | |
809 | size1 = d1->dict ? dictSize(d1->dict) : 0; | |
810 | size2 = d2->dict ? dictSize(d2->dict) : 0; | |
811 | return size1 - size2; | |
812 | } | |
813 | ||
814 | #define REDIS_AGGR_SUM 1 | |
815 | #define REDIS_AGGR_MIN 2 | |
816 | #define REDIS_AGGR_MAX 3 | |
817 | #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e)) | |
818 | ||
819 | inline static void zunionInterAggregate(double *target, double val, int aggregate) { | |
820 | if (aggregate == REDIS_AGGR_SUM) { | |
821 | *target = *target + val; | |
d9e28bcf PN |
822 | /* The result of adding two doubles is NaN when one variable |
823 | * is +inf and the other is -inf. When these numbers are added, | |
824 | * we maintain the convention of the result being 0.0. */ | |
825 | if (isnan(*target)) *target = 0.0; | |
e2641e09 | 826 | } else if (aggregate == REDIS_AGGR_MIN) { |
827 | *target = val < *target ? val : *target; | |
828 | } else if (aggregate == REDIS_AGGR_MAX) { | |
829 | *target = val > *target ? val : *target; | |
830 | } else { | |
831 | /* safety net */ | |
832 | redisPanic("Unknown ZUNION/INTER aggregate type"); | |
833 | } | |
834 | } | |
835 | ||
836 | void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) { | |
837 | int i, j, setnum; | |
838 | int aggregate = REDIS_AGGR_SUM; | |
839 | zsetopsrc *src; | |
840 | robj *dstobj; | |
841 | zset *dstzset; | |
69ef89f2 | 842 | zskiplistNode *znode; |
e2641e09 | 843 | dictIterator *di; |
844 | dictEntry *de; | |
8c1420ff | 845 | int touched = 0; |
e2641e09 | 846 | |
847 | /* expect setnum input keys to be given */ | |
848 | setnum = atoi(c->argv[2]->ptr); | |
849 | if (setnum < 1) { | |
3ab20376 PN |
850 | addReplyError(c, |
851 | "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE"); | |
e2641e09 | 852 | return; |
853 | } | |
854 | ||
855 | /* test if the expected number of keys would overflow */ | |
856 | if (3+setnum > c->argc) { | |
857 | addReply(c,shared.syntaxerr); | |
858 | return; | |
859 | } | |
860 | ||
861 | /* read keys to be used for input */ | |
862 | src = zmalloc(sizeof(zsetopsrc) * setnum); | |
863 | for (i = 0, j = 3; i < setnum; i++, j++) { | |
864 | robj *obj = lookupKeyWrite(c->db,c->argv[j]); | |
865 | if (!obj) { | |
866 | src[i].dict = NULL; | |
867 | } else { | |
868 | if (obj->type == REDIS_ZSET) { | |
869 | src[i].dict = ((zset*)obj->ptr)->dict; | |
870 | } else if (obj->type == REDIS_SET) { | |
871 | src[i].dict = (obj->ptr); | |
872 | } else { | |
873 | zfree(src); | |
874 | addReply(c,shared.wrongtypeerr); | |
875 | return; | |
876 | } | |
877 | } | |
878 | ||
879 | /* default all weights to 1 */ | |
880 | src[i].weight = 1.0; | |
881 | } | |
882 | ||
883 | /* parse optional extra arguments */ | |
884 | if (j < c->argc) { | |
885 | int remaining = c->argc - j; | |
886 | ||
887 | while (remaining) { | |
888 | if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) { | |
889 | j++; remaining--; | |
890 | for (i = 0; i < setnum; i++, j++, remaining--) { | |
673e1fb7 PN |
891 | if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight, |
892 | "weight value is not a double") != REDIS_OK) | |
893 | { | |
894 | zfree(src); | |
e2641e09 | 895 | return; |
673e1fb7 | 896 | } |
e2641e09 | 897 | } |
898 | } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) { | |
899 | j++; remaining--; | |
900 | if (!strcasecmp(c->argv[j]->ptr,"sum")) { | |
901 | aggregate = REDIS_AGGR_SUM; | |
902 | } else if (!strcasecmp(c->argv[j]->ptr,"min")) { | |
903 | aggregate = REDIS_AGGR_MIN; | |
904 | } else if (!strcasecmp(c->argv[j]->ptr,"max")) { | |
905 | aggregate = REDIS_AGGR_MAX; | |
906 | } else { | |
907 | zfree(src); | |
908 | addReply(c,shared.syntaxerr); | |
909 | return; | |
910 | } | |
911 | j++; remaining--; | |
912 | } else { | |
913 | zfree(src); | |
914 | addReply(c,shared.syntaxerr); | |
915 | return; | |
916 | } | |
917 | } | |
918 | } | |
919 | ||
920 | /* sort sets from the smallest to largest, this will improve our | |
921 | * algorithm's performance */ | |
922 | qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality); | |
923 | ||
924 | dstobj = createZsetObject(); | |
925 | dstzset = dstobj->ptr; | |
926 | ||
927 | if (op == REDIS_OP_INTER) { | |
928 | /* skip going over all entries if the smallest zset is NULL or empty */ | |
929 | if (src[0].dict && dictSize(src[0].dict) > 0) { | |
930 | /* precondition: as src[0].dict is non-empty and the zsets are ordered | |
931 | * from small to large, all src[i > 0].dict are non-empty too */ | |
932 | di = dictGetIterator(src[0].dict); | |
933 | while((de = dictNext(di)) != NULL) { | |
d433ebc6 | 934 | double score, value; |
e2641e09 | 935 | |
50a9fad5 | 936 | score = src[0].weight * zunionInterDictValue(de); |
e2641e09 | 937 | for (j = 1; j < setnum; j++) { |
938 | dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de)); | |
939 | if (other) { | |
940 | value = src[j].weight * zunionInterDictValue(other); | |
d433ebc6 | 941 | zunionInterAggregate(&score,value,aggregate); |
e2641e09 | 942 | } else { |
943 | break; | |
944 | } | |
945 | } | |
946 | ||
d433ebc6 PN |
947 | /* Only continue when present in every source dict. */ |
948 | if (j == setnum) { | |
e2641e09 | 949 | robj *o = dictGetEntryKey(de); |
d433ebc6 | 950 | znode = zslInsert(dstzset->zsl,score,o); |
e2641e09 | 951 | incrRefCount(o); /* added to skiplist */ |
69ef89f2 PN |
952 | dictAdd(dstzset->dict,o,&znode->score); |
953 | incrRefCount(o); /* added to dictionary */ | |
e2641e09 | 954 | } |
955 | } | |
956 | dictReleaseIterator(di); | |
957 | } | |
958 | } else if (op == REDIS_OP_UNION) { | |
959 | for (i = 0; i < setnum; i++) { | |
960 | if (!src[i].dict) continue; | |
961 | ||
962 | di = dictGetIterator(src[i].dict); | |
963 | while((de = dictNext(di)) != NULL) { | |
d433ebc6 PN |
964 | double score, value; |
965 | ||
e2641e09 | 966 | /* skip key when already processed */ |
d433ebc6 PN |
967 | if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL) |
968 | continue; | |
e2641e09 | 969 | |
d433ebc6 PN |
970 | /* initialize score */ |
971 | score = src[i].weight * zunionInterDictValue(de); | |
e2641e09 | 972 | |
973 | /* because the zsets are sorted by size, its only possible | |
974 | * for sets at larger indices to hold this entry */ | |
975 | for (j = (i+1); j < setnum; j++) { | |
976 | dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de)); | |
977 | if (other) { | |
978 | value = src[j].weight * zunionInterDictValue(other); | |
d433ebc6 | 979 | zunionInterAggregate(&score,value,aggregate); |
e2641e09 | 980 | } |
981 | } | |
982 | ||
983 | robj *o = dictGetEntryKey(de); | |
d433ebc6 | 984 | znode = zslInsert(dstzset->zsl,score,o); |
e2641e09 | 985 | incrRefCount(o); /* added to skiplist */ |
69ef89f2 PN |
986 | dictAdd(dstzset->dict,o,&znode->score); |
987 | incrRefCount(o); /* added to dictionary */ | |
e2641e09 | 988 | } |
989 | dictReleaseIterator(di); | |
990 | } | |
991 | } else { | |
992 | /* unknown operator */ | |
993 | redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION); | |
994 | } | |
995 | ||
8c1420ff | 996 | if (dbDelete(c->db,dstkey)) { |
cea8c5cd | 997 | signalModifiedKey(c->db,dstkey); |
8c1420ff | 998 | touched = 1; |
999 | server.dirty++; | |
1000 | } | |
e2641e09 | 1001 | if (dstzset->zsl->length) { |
1002 | dbAdd(c->db,dstkey,dstobj); | |
1003 | addReplyLongLong(c, dstzset->zsl->length); | |
cea8c5cd | 1004 | if (!touched) signalModifiedKey(c->db,dstkey); |
cbf7e107 | 1005 | server.dirty++; |
e2641e09 | 1006 | } else { |
1007 | decrRefCount(dstobj); | |
1008 | addReply(c, shared.czero); | |
1009 | } | |
1010 | zfree(src); | |
1011 | } | |
1012 | ||
1013 | void zunionstoreCommand(redisClient *c) { | |
1014 | zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION); | |
1015 | } | |
1016 | ||
1017 | void zinterstoreCommand(redisClient *c) { | |
1018 | zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER); | |
1019 | } | |
1020 | ||
1021 | void zrangeGenericCommand(redisClient *c, int reverse) { | |
1022 | robj *o; | |
1023 | long start; | |
1024 | long end; | |
1025 | int withscores = 0; | |
1026 | int llen; | |
1027 | int rangelen, j; | |
1028 | zset *zsetobj; | |
1029 | zskiplist *zsl; | |
1030 | zskiplistNode *ln; | |
1031 | robj *ele; | |
1032 | ||
1033 | if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) || | |
1034 | (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return; | |
1035 | ||
1036 | if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) { | |
1037 | withscores = 1; | |
1038 | } else if (c->argc >= 5) { | |
1039 | addReply(c,shared.syntaxerr); | |
1040 | return; | |
1041 | } | |
1042 | ||
1043 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL | |
1044 | || checkType(c,o,REDIS_ZSET)) return; | |
1045 | zsetobj = o->ptr; | |
1046 | zsl = zsetobj->zsl; | |
1047 | llen = zsl->length; | |
1048 | ||
1049 | /* convert negative indexes */ | |
1050 | if (start < 0) start = llen+start; | |
1051 | if (end < 0) end = llen+end; | |
1052 | if (start < 0) start = 0; | |
e2641e09 | 1053 | |
d0a4e24e PN |
1054 | /* Invariant: start >= 0, so this test will be true when end < 0. |
1055 | * The range is empty when start > end or start >= length. */ | |
e2641e09 | 1056 | if (start > end || start >= llen) { |
e2641e09 | 1057 | addReply(c,shared.emptymultibulk); |
1058 | return; | |
1059 | } | |
1060 | if (end >= llen) end = llen-1; | |
1061 | rangelen = (end-start)+1; | |
1062 | ||
1063 | /* check if starting point is trivial, before searching | |
1064 | * the element in log(N) time */ | |
1065 | if (reverse) { | |
a3004773 | 1066 | ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start); |
e2641e09 | 1067 | } else { |
1068 | ln = start == 0 ? | |
a3004773 | 1069 | zsl->header->level[0].forward : zslGetElementByRank(zsl, start+1); |
e2641e09 | 1070 | } |
1071 | ||
1072 | /* Return the result in form of a multi-bulk reply */ | |
0537e7bf | 1073 | addReplyMultiBulkLen(c,withscores ? (rangelen*2) : rangelen); |
e2641e09 | 1074 | for (j = 0; j < rangelen; j++) { |
1075 | ele = ln->obj; | |
1076 | addReplyBulk(c,ele); | |
1077 | if (withscores) | |
1078 | addReplyDouble(c,ln->score); | |
2159782b | 1079 | ln = reverse ? ln->backward : ln->level[0].forward; |
e2641e09 | 1080 | } |
1081 | } | |
1082 | ||
1083 | void zrangeCommand(redisClient *c) { | |
1084 | zrangeGenericCommand(c,0); | |
1085 | } | |
1086 | ||
1087 | void zrevrangeCommand(redisClient *c) { | |
1088 | zrangeGenericCommand(c,1); | |
1089 | } | |
1090 | ||
25bb8a44 PN |
1091 | /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT. |
1092 | * If "justcount", only the number of elements in the range is returned. */ | |
1093 | void genericZrangebyscoreCommand(redisClient *c, int reverse, int justcount) { | |
1094 | zrangespec range; | |
1095 | robj *o, *emptyreply; | |
1096 | zset *zsetobj; | |
1097 | zskiplist *zsl; | |
1098 | zskiplistNode *ln; | |
e2641e09 | 1099 | int offset = 0, limit = -1; |
1100 | int withscores = 0; | |
25bb8a44 PN |
1101 | unsigned long rangelen = 0; |
1102 | void *replylen = NULL; | |
22b9bf15 | 1103 | int minidx, maxidx; |
e2641e09 | 1104 | |
25bb8a44 | 1105 | /* Parse the range arguments. */ |
22b9bf15 PN |
1106 | if (reverse) { |
1107 | /* Range is given as [max,min] */ | |
1108 | maxidx = 2; minidx = 3; | |
1109 | } else { | |
1110 | /* Range is given as [min,max] */ | |
1111 | minidx = 2; maxidx = 3; | |
1112 | } | |
1113 | ||
1114 | if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) { | |
7236fdb2 PN |
1115 | addReplyError(c,"min or max is not a double"); |
1116 | return; | |
1117 | } | |
25bb8a44 PN |
1118 | |
1119 | /* Parse optional extra arguments. Note that ZCOUNT will exactly have | |
1120 | * 4 arguments, so we'll never enter the following code path. */ | |
1121 | if (c->argc > 4) { | |
1122 | int remaining = c->argc - 4; | |
1123 | int pos = 4; | |
1124 | ||
1125 | while (remaining) { | |
1126 | if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) { | |
1127 | pos++; remaining--; | |
1128 | withscores = 1; | |
1129 | } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) { | |
1130 | offset = atoi(c->argv[pos+1]->ptr); | |
1131 | limit = atoi(c->argv[pos+2]->ptr); | |
1132 | pos += 3; remaining -= 3; | |
1133 | } else { | |
1134 | addReply(c,shared.syntaxerr); | |
1135 | return; | |
1136 | } | |
1137 | } | |
e2641e09 | 1138 | } |
25bb8a44 PN |
1139 | |
1140 | /* Ok, lookup the key and get the range */ | |
1141 | emptyreply = justcount ? shared.czero : shared.emptymultibulk; | |
1142 | if ((o = lookupKeyReadOrReply(c,c->argv[1],emptyreply)) == NULL || | |
1143 | checkType(c,o,REDIS_ZSET)) return; | |
1144 | zsetobj = o->ptr; | |
1145 | zsl = zsetobj->zsl; | |
1146 | ||
22b9bf15 | 1147 | /* If reversed, get the last node in range as starting point. */ |
25bb8a44 | 1148 | if (reverse) { |
22b9bf15 | 1149 | ln = zslLastInRange(zsl,range); |
e2641e09 | 1150 | } else { |
22b9bf15 | 1151 | ln = zslFirstInRange(zsl,range); |
e2641e09 | 1152 | } |
1153 | ||
25bb8a44 PN |
1154 | /* No "first" element in the specified interval. */ |
1155 | if (ln == NULL) { | |
1156 | addReply(c,emptyreply); | |
e2641e09 | 1157 | return; |
1158 | } | |
1159 | ||
22b9bf15 PN |
1160 | /* We don't know in advance how many matching elements there are in the |
1161 | * list, so we push this object that will represent the multi-bulk length | |
1162 | * in the output buffer, and will "fix" it later */ | |
25bb8a44 PN |
1163 | if (!justcount) |
1164 | replylen = addDeferredMultiBulkLength(c); | |
e2641e09 | 1165 | |
25bb8a44 PN |
1166 | /* If there is an offset, just traverse the number of elements without |
1167 | * checking the score because that is done in the next loop. */ | |
1168 | while(ln && offset--) { | |
22b9bf15 | 1169 | ln = reverse ? ln->backward : ln->level[0].forward; |
25bb8a44 | 1170 | } |
e2641e09 | 1171 | |
25bb8a44 | 1172 | while (ln && limit--) { |
22b9bf15 | 1173 | /* Abort when the node is no longer in range. */ |
25bb8a44 | 1174 | if (reverse) { |
45290ad9 | 1175 | if (!zslValueGteMin(ln->score,&range)) break; |
25bb8a44 | 1176 | } else { |
45290ad9 | 1177 | if (!zslValueLteMax(ln->score,&range)) break; |
e2641e09 | 1178 | } |
25bb8a44 PN |
1179 | |
1180 | /* Do our magic */ | |
1181 | rangelen++; | |
1182 | if (!justcount) { | |
1183 | addReplyBulk(c,ln->obj); | |
1184 | if (withscores) | |
1185 | addReplyDouble(c,ln->score); | |
1186 | } | |
1187 | ||
22b9bf15 PN |
1188 | /* Move to next node */ |
1189 | ln = reverse ? ln->backward : ln->level[0].forward; | |
25bb8a44 PN |
1190 | } |
1191 | ||
1192 | if (justcount) { | |
1193 | addReplyLongLong(c,(long)rangelen); | |
1194 | } else { | |
1195 | setDeferredMultiBulkLength(c,replylen, | |
1196 | withscores ? (rangelen*2) : rangelen); | |
e2641e09 | 1197 | } |
1198 | } | |
1199 | ||
1200 | void zrangebyscoreCommand(redisClient *c) { | |
25bb8a44 PN |
1201 | genericZrangebyscoreCommand(c,0,0); |
1202 | } | |
1203 | ||
1204 | void zrevrangebyscoreCommand(redisClient *c) { | |
1205 | genericZrangebyscoreCommand(c,1,0); | |
e2641e09 | 1206 | } |
1207 | ||
1208 | void zcountCommand(redisClient *c) { | |
25bb8a44 | 1209 | genericZrangebyscoreCommand(c,0,1); |
e2641e09 | 1210 | } |
1211 | ||
1212 | void zcardCommand(redisClient *c) { | |
1213 | robj *o; | |
1214 | zset *zs; | |
1215 | ||
1216 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL || | |
1217 | checkType(c,o,REDIS_ZSET)) return; | |
1218 | ||
1219 | zs = o->ptr; | |
b70d3555 | 1220 | addReplyLongLong(c,zs->zsl->length); |
e2641e09 | 1221 | } |
1222 | ||
1223 | void zscoreCommand(redisClient *c) { | |
1224 | robj *o; | |
1225 | zset *zs; | |
1226 | dictEntry *de; | |
1227 | ||
1228 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL || | |
1229 | checkType(c,o,REDIS_ZSET)) return; | |
1230 | ||
1231 | zs = o->ptr; | |
75b41de8 | 1232 | c->argv[2] = tryObjectEncoding(c->argv[2]); |
e2641e09 | 1233 | de = dictFind(zs->dict,c->argv[2]); |
1234 | if (!de) { | |
1235 | addReply(c,shared.nullbulk); | |
1236 | } else { | |
1237 | double *score = dictGetEntryVal(de); | |
1238 | ||
1239 | addReplyDouble(c,*score); | |
1240 | } | |
1241 | } | |
1242 | ||
1243 | void zrankGenericCommand(redisClient *c, int reverse) { | |
1244 | robj *o; | |
1245 | zset *zs; | |
1246 | zskiplist *zsl; | |
1247 | dictEntry *de; | |
1248 | unsigned long rank; | |
1249 | double *score; | |
1250 | ||
1251 | if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL || | |
1252 | checkType(c,o,REDIS_ZSET)) return; | |
1253 | ||
1254 | zs = o->ptr; | |
1255 | zsl = zs->zsl; | |
75b41de8 | 1256 | c->argv[2] = tryObjectEncoding(c->argv[2]); |
e2641e09 | 1257 | de = dictFind(zs->dict,c->argv[2]); |
1258 | if (!de) { | |
1259 | addReply(c,shared.nullbulk); | |
1260 | return; | |
1261 | } | |
1262 | ||
1263 | score = dictGetEntryVal(de); | |
a3004773 | 1264 | rank = zslGetRank(zsl, *score, c->argv[2]); |
e2641e09 | 1265 | if (rank) { |
1266 | if (reverse) { | |
1267 | addReplyLongLong(c, zsl->length - rank); | |
1268 | } else { | |
1269 | addReplyLongLong(c, rank-1); | |
1270 | } | |
1271 | } else { | |
1272 | addReply(c,shared.nullbulk); | |
1273 | } | |
1274 | } | |
1275 | ||
1276 | void zrankCommand(redisClient *c) { | |
1277 | zrankGenericCommand(c, 0); | |
1278 | } | |
1279 | ||
1280 | void zrevrankCommand(redisClient *c) { | |
1281 | zrankGenericCommand(c, 1); | |
1282 | } |