]> git.saurik.com Git - redis.git/blob - src/t_zset.c
c71be90a2c1012f8a9f8b9640067324f52d2f196
[redis.git] / src / t_zset.c
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)+level*sizeof(struct zskiplistLevel));
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++) {
42 zsl->header->level[j].forward = NULL;
43 zsl->header->level[j].span = 0;
44 }
45 zsl->header->backward = NULL;
46 zsl->tail = NULL;
47 return zsl;
48 }
49
50 void zslFreeNode(zskiplistNode *node) {
51 decrRefCount(node->obj);
52 zfree(node);
53 }
54
55 void zslFree(zskiplist *zsl) {
56 zskiplistNode *node = zsl->header->level[0].forward, *next;
57
58 zfree(zsl->header);
59 while(node) {
60 next = node->level[0].forward;
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
74 zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
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];
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;
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;
101 update[i]->level[i].span = zsl->length;
102 }
103 zsl->level = level;
104 }
105 x = zslCreateNode(level,score,obj);
106 for (i = 0; i < level; i++) {
107 x->level[i].forward = update[i]->level[i].forward;
108 update[i]->level[i].forward = x;
109
110 /* update span covered by update[i] as x is inserted here */
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;
113 }
114
115 /* increment span for untouched levels */
116 for (i = level; i < zsl->level; i++) {
117 update[i]->level[i].span++;
118 }
119
120 x->backward = (update[0] == zsl->header) ? NULL : update[0];
121 if (x->level[0].forward)
122 x->level[0].forward->backward = x;
123 else
124 zsl->tail = x;
125 zsl->length++;
126 return x;
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++) {
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;
136 } else {
137 update[i]->level[i].span -= 1;
138 }
139 }
140 if (x->level[0].forward) {
141 x->level[0].forward->backward = x->backward;
142 } else {
143 zsl->tail = x->backward;
144 }
145 while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
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--) {
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;
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. */
166 x = x->level[0].forward;
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
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
183 static int zslValueGteMin(double value, zrangespec *spec) {
184 return spec->minex ? (value > spec->min) : (value >= spec->min);
185 }
186
187 static int zslValueLteMax(double value, zrangespec *spec) {
188 return spec->maxex ? (value < spec->max) : (value <= spec->max);
189 }
190
191 static int zslValueInRange(double value, zrangespec *spec) {
192 return zslValueGteMin(value,spec) && zslValueLteMax(value,spec);
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
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;
203 x = zsl->tail;
204 if (x == NULL || !zslValueGteMin(x->score,range))
205 return 0;
206 x = zsl->header->level[0].forward;
207 if (x == NULL || !zslValueLteMax(x->score,range))
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 &&
225 !zslValueGteMin(x->level[i].forward->score,&range))
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 &&
249 zslValueLteMax(x->level[i].forward->score,&range))
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
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. */
263 unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec range, dict *dict) {
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--) {
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;
274 update[i] = x;
275 }
276
277 /* Current node is the last with score < or <= min. */
278 x = x->level[0].forward;
279
280 /* Delete nodes while in range. */
281 while (x && (range.maxex ? x->score < range.max : x->score <= range.max)) {
282 zskiplistNode *next = x->level[0].forward;
283 zslDeleteNode(zsl,x,update);
284 dictDelete(dict,x->obj);
285 zslFreeNode(x);
286 removed++;
287 x = next;
288 }
289 return removed;
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--) {
301 while (x->level[i].forward && (traversed + x->level[i].span) < start) {
302 traversed += x->level[i].span;
303 x = x->level[i].forward;
304 }
305 update[i] = x;
306 }
307
308 traversed++;
309 x = x->level[0].forward;
310 while (x && traversed <= end) {
311 zskiplistNode *next = x->level[0].forward;
312 zslDeleteNode(zsl,x,update);
313 dictDelete(dict,x->obj);
314 zslFreeNode(x);
315 removed++;
316 traversed++;
317 x = next;
318 }
319 return removed;
320 }
321
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. */
326 unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
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--) {
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;
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. */
350 zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
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--) {
357 while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
358 {
359 traversed += x->level[i].span;
360 x = x->level[i].forward;
361 }
362 if (traversed == rank) {
363 return x;
364 }
365 }
366 return NULL;
367 }
368
369 /* Populate the rangespec according to the objects min and max. */
370 static int zslParseRange(robj *min, robj *max, zrangespec *spec) {
371 char *eptr;
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] == '(') {
382 spec->min = strtod((char*)min->ptr+1,&eptr);
383 if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
384 spec->minex = 1;
385 } else {
386 spec->min = strtod((char*)min->ptr,&eptr);
387 if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
388 }
389 }
390 if (max->encoding == REDIS_ENCODING_INT) {
391 spec->max = (long)max->ptr;
392 } else {
393 if (((char*)max->ptr)[0] == '(') {
394 spec->max = strtod((char*)max->ptr+1,&eptr);
395 if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
396 spec->maxex = 1;
397 } else {
398 spec->max = strtod((char*)max->ptr,&eptr);
399 if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
400 }
401 }
402
403 return REDIS_OK;
404 }
405
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
452 unsigned int zzlLength(robj *zobj) {
453 unsigned char *zl = zobj->ptr;
454 return ziplistLen(zl)/2;
455 }
456
457 /* Returns if there is a part of the zset is in range. Should only be used
458 * internally by zzlFirstInRange and zzlLastInRange. */
459 int zzlIsInRange(unsigned char *zl, zrangespec *range) {
460 unsigned char *p;
461 double score;
462
463 /* Test for ranges that will always be empty. */
464 if (range->min > range->max ||
465 (range->min == range->max && (range->minex || range->maxex)))
466 return 0;
467
468 p = ziplistIndex(zl,-1); /* Last score. */
469 redisAssert(p != NULL);
470 score = zzlGetScore(p);
471 if (!zslValueGteMin(score,range))
472 return 0;
473
474 p = ziplistIndex(zl,1); /* First score. */
475 redisAssert(p != NULL);
476 score = zzlGetScore(p);
477 if (!zslValueLteMax(score,range))
478 return 0;
479
480 return 1;
481 }
482
483 /* Find pointer to the first element contained in the specified range.
484 * Returns NULL when no element is contained in the range. */
485 unsigned char *zzlFirstInRange(robj *zobj, zrangespec range) {
486 unsigned char *zl = zobj->ptr;
487 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
488 double score;
489
490 /* If everything is out of range, return early. */
491 if (!zzlIsInRange(zl,&range)) return NULL;
492
493 while (eptr != NULL) {
494 sptr = ziplistNext(zl,eptr);
495 redisAssert(sptr != NULL);
496
497 score = zzlGetScore(sptr);
498 if (zslValueGteMin(score,&range))
499 return eptr;
500
501 /* Move to next element. */
502 eptr = ziplistNext(zl,sptr);
503 }
504
505 return NULL;
506 }
507
508 /* Find pointer to the last element contained in the specified range.
509 * Returns NULL when no element is contained in the range. */
510 unsigned char *zzlLastInRange(robj *zobj, zrangespec range) {
511 unsigned char *zl = zobj->ptr;
512 unsigned char *eptr = ziplistIndex(zl,-2), *sptr;
513 double score;
514
515 /* If everything is out of range, return early. */
516 if (!zzlIsInRange(zl,&range)) return NULL;
517
518 while (eptr != NULL) {
519 sptr = ziplistNext(zl,eptr);
520 redisAssert(sptr != NULL);
521
522 score = zzlGetScore(sptr);
523 if (zslValueLteMax(score,&range))
524 return eptr;
525
526 /* Move to previous element by moving to the score of previous element.
527 * When this returns NULL, we know there also is no element. */
528 sptr = ziplistPrev(zl,eptr);
529 if (sptr != NULL)
530 redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
531 else
532 eptr = NULL;
533 }
534
535 return NULL;
536 }
537
538 unsigned char *zzlFind(robj *zobj, robj *ele, double *score) {
539 unsigned char *zl = zobj->ptr;
540 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
541
542 ele = getDecodedObject(ele);
543 while (eptr != NULL) {
544 sptr = ziplistNext(zl,eptr);
545 redisAssert(sptr != NULL);
546
547 if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) {
548 /* Matching element, pull out score. */
549 if (score != NULL) *score = zzlGetScore(sptr);
550 decrRefCount(ele);
551 return eptr;
552 }
553
554 /* Move to next element. */
555 eptr = ziplistNext(zl,sptr);
556 }
557
558 decrRefCount(ele);
559 return NULL;
560 }
561
562 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
563 * don't want to modify the one given as argument. */
564 int zzlDelete(robj *zobj, unsigned char *eptr) {
565 unsigned char *zl = zobj->ptr;
566 unsigned char *p = eptr;
567
568 /* TODO: add function to ziplist API to delete N elements from offset. */
569 zl = ziplistDelete(zl,&p);
570 zl = ziplistDelete(zl,&p);
571 zobj->ptr = zl;
572 return REDIS_OK;
573 }
574
575 int zzlInsertAt(robj *zobj, robj *ele, double score, unsigned char *eptr) {
576 unsigned char *zl = zobj->ptr;
577 unsigned char *sptr;
578 char scorebuf[128];
579 int scorelen;
580 int offset;
581
582 redisAssert(ele->encoding == REDIS_ENCODING_RAW);
583 scorelen = d2string(scorebuf,sizeof(scorebuf),score);
584 if (eptr == NULL) {
585 zl = ziplistPush(zl,ele->ptr,sdslen(ele->ptr),ZIPLIST_TAIL);
586 zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL);
587 } else {
588 /* Keep offset relative to zl, as it might be re-allocated. */
589 offset = eptr-zl;
590 zl = ziplistInsert(zl,eptr,ele->ptr,sdslen(ele->ptr));
591 eptr = zl+offset;
592
593 /* Insert score after the element. */
594 redisAssert((sptr = ziplistNext(zl,eptr)) != NULL);
595 zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen);
596 }
597
598 zobj->ptr = zl;
599 return REDIS_OK;
600 }
601
602 /* Insert (element,score) pair in ziplist. This function assumes the element is
603 * not yet present in the list. */
604 int zzlInsert(robj *zobj, robj *ele, double score) {
605 unsigned char *zl = zobj->ptr;
606 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
607 double s;
608
609 ele = getDecodedObject(ele);
610 while (eptr != NULL) {
611 sptr = ziplistNext(zl,eptr);
612 redisAssert(sptr != NULL);
613 s = zzlGetScore(sptr);
614
615 if (s > score) {
616 /* First element with score larger than score for element to be
617 * inserted. This means we should take its spot in the list to
618 * maintain ordering. */
619 zzlInsertAt(zobj,ele,score,eptr);
620 break;
621 } else if (s == score) {
622 /* Ensure lexicographical ordering for elements. */
623 if (zzlCompareElements(eptr,ele->ptr,sdslen(ele->ptr)) < 0) {
624 zzlInsertAt(zobj,ele,score,eptr);
625 break;
626 }
627 }
628
629 /* Move to next element. */
630 eptr = ziplistNext(zl,sptr);
631 }
632
633 /* Push on tail of list when it was not yet inserted. */
634 if (eptr == NULL)
635 zzlInsertAt(zobj,ele,score,NULL);
636
637 decrRefCount(ele);
638 return REDIS_OK;
639 }
640
641 unsigned long zzlDeleteRangeByScore(robj *zobj, zrangespec range) {
642 unsigned char *zl = zobj->ptr;
643 unsigned char *eptr, *sptr;
644 double score;
645 unsigned long deleted = 0;
646
647 eptr = zzlFirstInRange(zobj,range);
648 if (eptr == NULL) return deleted;
649
650
651 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
652 * byte and ziplistNext will return NULL. */
653 while ((sptr = ziplistNext(zl,eptr)) != NULL) {
654 score = zzlGetScore(sptr);
655 if (zslValueLteMax(score,&range)) {
656 /* Delete both the element and the score. */
657 zl = ziplistDelete(zl,&eptr);
658 zl = ziplistDelete(zl,&eptr);
659 deleted++;
660 } else {
661 /* No longer in range. */
662 break;
663 }
664 }
665
666 return deleted;
667 }
668
669 /* Delete all the elements with rank between start and end from the skiplist.
670 * Start and end are inclusive. Note that start and end need to be 1-based */
671 unsigned long zzlDeleteRangeByRank(robj *zobj, unsigned int start, unsigned int end) {
672 unsigned int num = (end-start)+1;
673 zobj->ptr = ziplistDeleteRange(zobj->ptr,2*(start-1),2*num);
674 return num;
675 }
676
677 /*-----------------------------------------------------------------------------
678 * Common sorted set API
679 *----------------------------------------------------------------------------*/
680
681 int zsLength(robj *zobj) {
682 int length = -1;
683 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
684 length = zzlLength(zobj);
685 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
686 length = ((zset*)zobj->ptr)->zsl->length;
687 } else {
688 redisPanic("Unknown sorted set encoding");
689 }
690 return length;
691 }
692
693 /*-----------------------------------------------------------------------------
694 * Sorted set commands
695 *----------------------------------------------------------------------------*/
696
697 /* This generic command implements both ZADD and ZINCRBY. */
698 void zaddGenericCommand(redisClient *c, int incr) {
699 static char *nanerr = "resulting score is not a number (NaN)";
700 robj *key = c->argv[1];
701 robj *ele;
702 robj *zobj;
703 robj *curobj;
704 double score, curscore = 0.0;
705
706 if (getDoubleFromObjectOrReply(c,c->argv[2],&score,NULL) != REDIS_OK)
707 return;
708
709 zobj = lookupKeyWrite(c->db,key);
710 if (zobj == NULL) {
711 zobj = createZsetZiplistObject();
712 dbAdd(c->db,key,zobj);
713 } else {
714 if (zobj->type != REDIS_ZSET) {
715 addReply(c,shared.wrongtypeerr);
716 return;
717 }
718 }
719
720 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
721 unsigned char *eptr;
722
723 /* Prefer non-encoded element when dealing with ziplists. */
724 ele = c->argv[3];
725 if ((eptr = zzlFind(zobj,ele,&curscore)) != NULL) {
726 if (incr) {
727 score += curscore;
728 if (isnan(score)) {
729 addReplyError(c,nanerr);
730 /* Don't need to check if the sorted set is empty, because
731 * we know it has at least one element. */
732 return;
733 }
734 }
735
736 /* Remove and re-insert when score changed. */
737 if (score != curscore) {
738 redisAssert(zzlDelete(zobj,eptr) == REDIS_OK);
739 redisAssert(zzlInsert(zobj,ele,score) == REDIS_OK);
740
741 signalModifiedKey(c->db,key);
742 server.dirty++;
743 }
744
745 if (incr) /* ZINCRBY */
746 addReplyDouble(c,score);
747 else /* ZADD */
748 addReply(c,shared.czero);
749 } else {
750 redisAssert(zzlInsert(zobj,ele,score) == REDIS_OK);
751
752 signalModifiedKey(c->db,key);
753 server.dirty++;
754
755 if (incr) /* ZINCRBY */
756 addReplyDouble(c,score);
757 else /* ZADD */
758 addReply(c,shared.cone);
759 }
760 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
761 zset *zs = zobj->ptr;
762 zskiplistNode *znode;
763 dictEntry *de;
764
765 ele = c->argv[3] = tryObjectEncoding(c->argv[3]);
766 de = dictFind(zs->dict,ele);
767 if (de != NULL) {
768 curobj = dictGetEntryKey(de);
769 curscore = *(double*)dictGetEntryVal(de);
770
771 if (incr) {
772 score += curscore;
773 if (isnan(score)) {
774 addReplyError(c,nanerr);
775 /* Don't need to check if the sorted set is empty, because
776 * we know it has at least one element. */
777 return;
778 }
779 }
780
781 /* Remove and re-insert when score changed. We can safely delete
782 * the key object from the skiplist, since the dictionary still has
783 * a reference to it. */
784 if (score != curscore) {
785 redisAssert(zslDelete(zs->zsl,curscore,curobj));
786 znode = zslInsert(zs->zsl,score,curobj);
787 incrRefCount(curobj); /* Re-inserted in skiplist. */
788 dictGetEntryVal(de) = &znode->score; /* Update score ptr. */
789
790 signalModifiedKey(c->db,key);
791 server.dirty++;
792 }
793
794 if (incr) /* ZINCRBY */
795 addReplyDouble(c,score);
796 else /* ZADD */
797 addReply(c,shared.czero);
798 } else {
799 znode = zslInsert(zs->zsl,score,ele);
800 incrRefCount(ele); /* Inserted in skiplist. */
801 redisAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
802 incrRefCount(ele); /* Added to dictionary. */
803
804 signalModifiedKey(c->db,key);
805 server.dirty++;
806
807 if (incr) /* ZINCRBY */
808 addReplyDouble(c,score);
809 else /* ZADD */
810 addReply(c,shared.cone);
811 }
812 } else {
813 redisPanic("Unknown sorted set encoding");
814 }
815 }
816
817 void zaddCommand(redisClient *c) {
818 zaddGenericCommand(c,0);
819 }
820
821 void zincrbyCommand(redisClient *c) {
822 zaddGenericCommand(c,1);
823 }
824
825 void zremCommand(redisClient *c) {
826 robj *key = c->argv[1];
827 robj *ele = c->argv[2];
828 robj *zobj;
829
830 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
831 checkType(c,zobj,REDIS_ZSET)) return;
832
833 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
834 unsigned char *eptr;
835
836 if ((eptr = zzlFind(zobj,ele,NULL)) != NULL) {
837 redisAssert(zzlDelete(zobj,eptr) == REDIS_OK);
838 if (zzlLength(zobj) == 0) dbDelete(c->db,key);
839 } else {
840 addReply(c,shared.czero);
841 return;
842 }
843 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
844 zset *zs = zobj->ptr;
845 dictEntry *de;
846 double score;
847
848 de = dictFind(zs->dict,ele);
849 if (de != NULL) {
850 /* Delete from the skiplist */
851 score = *(double*)dictGetEntryVal(de);
852 redisAssert(zslDelete(zs->zsl,score,ele));
853
854 /* Delete from the hash table */
855 dictDelete(zs->dict,ele);
856 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
857 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
858 } else {
859 addReply(c,shared.czero);
860 return;
861 }
862 } else {
863 redisPanic("Unknown sorted set encoding");
864 }
865
866 signalModifiedKey(c->db,key);
867 server.dirty++;
868 addReply(c,shared.cone);
869 }
870
871 void zremrangebyscoreCommand(redisClient *c) {
872 robj *key = c->argv[1];
873 robj *zobj;
874 zrangespec range;
875 unsigned long deleted;
876
877 /* Parse the range arguments. */
878 if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
879 addReplyError(c,"min or max is not a double");
880 return;
881 }
882
883 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
884 checkType(c,zobj,REDIS_ZSET)) return;
885
886 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
887 deleted = zzlDeleteRangeByScore(zobj,range);
888 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
889 zset *zs = zobj->ptr;
890 deleted = zslDeleteRangeByScore(zs->zsl,range,zs->dict);
891 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
892 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
893 } else {
894 redisPanic("Unknown sorted set encoding");
895 }
896
897 if (deleted) signalModifiedKey(c->db,key);
898 server.dirty += deleted;
899 addReplyLongLong(c,deleted);
900 }
901
902 void zremrangebyrankCommand(redisClient *c) {
903 robj *key = c->argv[1];
904 robj *zobj;
905 long start;
906 long end;
907 int llen;
908 unsigned long deleted;
909
910 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
911 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
912
913 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
914 checkType(c,zobj,REDIS_ZSET)) return;
915
916 /* Sanitize indexes. */
917 llen = zsLength(zobj);
918 if (start < 0) start = llen+start;
919 if (end < 0) end = llen+end;
920 if (start < 0) start = 0;
921
922 /* Invariant: start >= 0, so this test will be true when end < 0.
923 * The range is empty when start > end or start >= length. */
924 if (start > end || start >= llen) {
925 addReply(c,shared.czero);
926 return;
927 }
928 if (end >= llen) end = llen-1;
929
930 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
931 /* Correct for 1-based rank. */
932 deleted = zzlDeleteRangeByRank(zobj,start+1,end+1);
933 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
934 zset *zs = zobj->ptr;
935
936 /* Correct for 1-based rank. */
937 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
938 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
939 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
940 } else {
941 redisPanic("Unknown sorted set encoding");
942 }
943
944 if (deleted) signalModifiedKey(c->db,key);
945 server.dirty += deleted;
946 addReplyLongLong(c,deleted);
947 }
948
949 typedef struct {
950 dict *dict;
951 double weight;
952 } zsetopsrc;
953
954 int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
955 zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
956 unsigned long size1, size2;
957 size1 = d1->dict ? dictSize(d1->dict) : 0;
958 size2 = d2->dict ? dictSize(d2->dict) : 0;
959 return size1 - size2;
960 }
961
962 #define REDIS_AGGR_SUM 1
963 #define REDIS_AGGR_MIN 2
964 #define REDIS_AGGR_MAX 3
965 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
966
967 inline static void zunionInterAggregate(double *target, double val, int aggregate) {
968 if (aggregate == REDIS_AGGR_SUM) {
969 *target = *target + val;
970 /* The result of adding two doubles is NaN when one variable
971 * is +inf and the other is -inf. When these numbers are added,
972 * we maintain the convention of the result being 0.0. */
973 if (isnan(*target)) *target = 0.0;
974 } else if (aggregate == REDIS_AGGR_MIN) {
975 *target = val < *target ? val : *target;
976 } else if (aggregate == REDIS_AGGR_MAX) {
977 *target = val > *target ? val : *target;
978 } else {
979 /* safety net */
980 redisPanic("Unknown ZUNION/INTER aggregate type");
981 }
982 }
983
984 void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
985 int i, j, setnum;
986 int aggregate = REDIS_AGGR_SUM;
987 zsetopsrc *src;
988 robj *dstobj;
989 zset *dstzset;
990 zskiplistNode *znode;
991 dictIterator *di;
992 dictEntry *de;
993 int touched = 0;
994
995 /* expect setnum input keys to be given */
996 setnum = atoi(c->argv[2]->ptr);
997 if (setnum < 1) {
998 addReplyError(c,
999 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1000 return;
1001 }
1002
1003 /* test if the expected number of keys would overflow */
1004 if (3+setnum > c->argc) {
1005 addReply(c,shared.syntaxerr);
1006 return;
1007 }
1008
1009 /* read keys to be used for input */
1010 src = zmalloc(sizeof(zsetopsrc) * setnum);
1011 for (i = 0, j = 3; i < setnum; i++, j++) {
1012 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
1013 if (!obj) {
1014 src[i].dict = NULL;
1015 } else {
1016 if (obj->type == REDIS_ZSET) {
1017 src[i].dict = ((zset*)obj->ptr)->dict;
1018 } else if (obj->type == REDIS_SET) {
1019 src[i].dict = (obj->ptr);
1020 } else {
1021 zfree(src);
1022 addReply(c,shared.wrongtypeerr);
1023 return;
1024 }
1025 }
1026
1027 /* default all weights to 1 */
1028 src[i].weight = 1.0;
1029 }
1030
1031 /* parse optional extra arguments */
1032 if (j < c->argc) {
1033 int remaining = c->argc - j;
1034
1035 while (remaining) {
1036 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
1037 j++; remaining--;
1038 for (i = 0; i < setnum; i++, j++, remaining--) {
1039 if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
1040 "weight value is not a double") != REDIS_OK)
1041 {
1042 zfree(src);
1043 return;
1044 }
1045 }
1046 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
1047 j++; remaining--;
1048 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
1049 aggregate = REDIS_AGGR_SUM;
1050 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
1051 aggregate = REDIS_AGGR_MIN;
1052 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
1053 aggregate = REDIS_AGGR_MAX;
1054 } else {
1055 zfree(src);
1056 addReply(c,shared.syntaxerr);
1057 return;
1058 }
1059 j++; remaining--;
1060 } else {
1061 zfree(src);
1062 addReply(c,shared.syntaxerr);
1063 return;
1064 }
1065 }
1066 }
1067
1068 /* sort sets from the smallest to largest, this will improve our
1069 * algorithm's performance */
1070 qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);
1071
1072 dstobj = createZsetObject();
1073 dstzset = dstobj->ptr;
1074
1075 if (op == REDIS_OP_INTER) {
1076 /* skip going over all entries if the smallest zset is NULL or empty */
1077 if (src[0].dict && dictSize(src[0].dict) > 0) {
1078 /* precondition: as src[0].dict is non-empty and the zsets are ordered
1079 * from small to large, all src[i > 0].dict are non-empty too */
1080 di = dictGetIterator(src[0].dict);
1081 while((de = dictNext(di)) != NULL) {
1082 double score, value;
1083
1084 score = src[0].weight * zunionInterDictValue(de);
1085 for (j = 1; j < setnum; j++) {
1086 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
1087 if (other) {
1088 value = src[j].weight * zunionInterDictValue(other);
1089 zunionInterAggregate(&score,value,aggregate);
1090 } else {
1091 break;
1092 }
1093 }
1094
1095 /* Only continue when present in every source dict. */
1096 if (j == setnum) {
1097 robj *o = dictGetEntryKey(de);
1098 znode = zslInsert(dstzset->zsl,score,o);
1099 incrRefCount(o); /* added to skiplist */
1100 dictAdd(dstzset->dict,o,&znode->score);
1101 incrRefCount(o); /* added to dictionary */
1102 }
1103 }
1104 dictReleaseIterator(di);
1105 }
1106 } else if (op == REDIS_OP_UNION) {
1107 for (i = 0; i < setnum; i++) {
1108 if (!src[i].dict) continue;
1109
1110 di = dictGetIterator(src[i].dict);
1111 while((de = dictNext(di)) != NULL) {
1112 double score, value;
1113
1114 /* skip key when already processed */
1115 if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL)
1116 continue;
1117
1118 /* initialize score */
1119 score = src[i].weight * zunionInterDictValue(de);
1120
1121 /* because the zsets are sorted by size, its only possible
1122 * for sets at larger indices to hold this entry */
1123 for (j = (i+1); j < setnum; j++) {
1124 dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
1125 if (other) {
1126 value = src[j].weight * zunionInterDictValue(other);
1127 zunionInterAggregate(&score,value,aggregate);
1128 }
1129 }
1130
1131 robj *o = dictGetEntryKey(de);
1132 znode = zslInsert(dstzset->zsl,score,o);
1133 incrRefCount(o); /* added to skiplist */
1134 dictAdd(dstzset->dict,o,&znode->score);
1135 incrRefCount(o); /* added to dictionary */
1136 }
1137 dictReleaseIterator(di);
1138 }
1139 } else {
1140 /* unknown operator */
1141 redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
1142 }
1143
1144 if (dbDelete(c->db,dstkey)) {
1145 signalModifiedKey(c->db,dstkey);
1146 touched = 1;
1147 server.dirty++;
1148 }
1149 if (dstzset->zsl->length) {
1150 dbAdd(c->db,dstkey,dstobj);
1151 addReplyLongLong(c, dstzset->zsl->length);
1152 if (!touched) signalModifiedKey(c->db,dstkey);
1153 server.dirty++;
1154 } else {
1155 decrRefCount(dstobj);
1156 addReply(c, shared.czero);
1157 }
1158 zfree(src);
1159 }
1160
1161 void zunionstoreCommand(redisClient *c) {
1162 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
1163 }
1164
1165 void zinterstoreCommand(redisClient *c) {
1166 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
1167 }
1168
1169 void zrangeGenericCommand(redisClient *c, int reverse) {
1170 robj *key = c->argv[1];
1171 robj *zobj;
1172 int withscores = 0;
1173 long start;
1174 long end;
1175 int llen;
1176 int rangelen;
1177
1178 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
1179 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
1180
1181 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
1182 withscores = 1;
1183 } else if (c->argc >= 5) {
1184 addReply(c,shared.syntaxerr);
1185 return;
1186 }
1187
1188 if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
1189 || checkType(c,zobj,REDIS_ZSET)) return;
1190
1191 /* Sanitize indexes. */
1192 llen = zsLength(zobj);
1193 if (start < 0) start = llen+start;
1194 if (end < 0) end = llen+end;
1195 if (start < 0) start = 0;
1196
1197 /* Invariant: start >= 0, so this test will be true when end < 0.
1198 * The range is empty when start > end or start >= length. */
1199 if (start > end || start >= llen) {
1200 addReply(c,shared.emptymultibulk);
1201 return;
1202 }
1203 if (end >= llen) end = llen-1;
1204 rangelen = (end-start)+1;
1205
1206 /* Return the result in form of a multi-bulk reply */
1207 addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);
1208
1209 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1210 unsigned char *zl = zobj->ptr;
1211 unsigned char *eptr, *sptr;
1212 unsigned char *vstr;
1213 unsigned int vlen;
1214 long long vlong;
1215
1216 if (reverse)
1217 eptr = ziplistIndex(zl,-2-(2*start));
1218 else
1219 eptr = ziplistIndex(zl,2*start);
1220
1221 while (rangelen--) {
1222 redisAssert(eptr != NULL);
1223 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
1224 if (vstr == NULL)
1225 addReplyBulkLongLong(c,vlong);
1226 else
1227 addReplyBulkCBuffer(c,vstr,vlen);
1228
1229 if (withscores) {
1230 sptr = ziplistNext(zl,eptr);
1231 redisAssert(sptr != NULL);
1232 addReplyDouble(c,zzlGetScore(sptr));
1233 }
1234
1235 if (reverse) {
1236 /* Move to previous element by moving to the score of previous
1237 * element. When NULL, we know there also is no element. */
1238 sptr = ziplistPrev(zl,eptr);
1239 if (sptr != NULL) {
1240 eptr = ziplistPrev(zl,sptr);
1241 redisAssert(eptr != NULL);
1242 } else {
1243 eptr = NULL;
1244 }
1245 } else {
1246 sptr = ziplistNext(zl,eptr);
1247 redisAssert(sptr != NULL);
1248 eptr = ziplistNext(zl,sptr);
1249 }
1250 }
1251
1252 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1253 zset *zs = zobj->ptr;
1254 zskiplist *zsl = zs->zsl;
1255 zskiplistNode *ln;
1256 robj *ele;
1257
1258 /* Check if starting point is trivial, before doing log(N) lookup. */
1259 if (reverse) {
1260 ln = zsl->tail;
1261 if (start > 0)
1262 ln = zslGetElementByRank(zsl,llen-start);
1263 } else {
1264 ln = zsl->header->level[0].forward;
1265 if (start > 0)
1266 ln = zslGetElementByRank(zsl,start+1);
1267 }
1268
1269 while(rangelen--) {
1270 redisAssert(ln != NULL);
1271 ele = ln->obj;
1272 addReplyBulk(c,ele);
1273 if (withscores)
1274 addReplyDouble(c,ln->score);
1275 ln = reverse ? ln->backward : ln->level[0].forward;
1276 }
1277 } else {
1278 redisPanic("Unknown sorted set encoding");
1279 }
1280 }
1281
1282 void zrangeCommand(redisClient *c) {
1283 zrangeGenericCommand(c,0);
1284 }
1285
1286 void zrevrangeCommand(redisClient *c) {
1287 zrangeGenericCommand(c,1);
1288 }
1289
1290 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1291 * If "justcount", only the number of elements in the range is returned. */
1292 void genericZrangebyscoreCommand(redisClient *c, int reverse, int justcount) {
1293 zrangespec range;
1294 robj *o, *emptyreply;
1295 zset *zsetobj;
1296 zskiplist *zsl;
1297 zskiplistNode *ln;
1298 int offset = 0, limit = -1;
1299 int withscores = 0;
1300 unsigned long rangelen = 0;
1301 void *replylen = NULL;
1302 int minidx, maxidx;
1303
1304 /* Parse the range arguments. */
1305 if (reverse) {
1306 /* Range is given as [max,min] */
1307 maxidx = 2; minidx = 3;
1308 } else {
1309 /* Range is given as [min,max] */
1310 minidx = 2; maxidx = 3;
1311 }
1312
1313 if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) {
1314 addReplyError(c,"min or max is not a double");
1315 return;
1316 }
1317
1318 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1319 * 4 arguments, so we'll never enter the following code path. */
1320 if (c->argc > 4) {
1321 int remaining = c->argc - 4;
1322 int pos = 4;
1323
1324 while (remaining) {
1325 if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) {
1326 pos++; remaining--;
1327 withscores = 1;
1328 } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
1329 offset = atoi(c->argv[pos+1]->ptr);
1330 limit = atoi(c->argv[pos+2]->ptr);
1331 pos += 3; remaining -= 3;
1332 } else {
1333 addReply(c,shared.syntaxerr);
1334 return;
1335 }
1336 }
1337 }
1338
1339 /* Ok, lookup the key and get the range */
1340 emptyreply = justcount ? shared.czero : shared.emptymultibulk;
1341 if ((o = lookupKeyReadOrReply(c,c->argv[1],emptyreply)) == NULL ||
1342 checkType(c,o,REDIS_ZSET)) return;
1343 zsetobj = o->ptr;
1344 zsl = zsetobj->zsl;
1345
1346 /* If reversed, get the last node in range as starting point. */
1347 if (reverse) {
1348 ln = zslLastInRange(zsl,range);
1349 } else {
1350 ln = zslFirstInRange(zsl,range);
1351 }
1352
1353 /* No "first" element in the specified interval. */
1354 if (ln == NULL) {
1355 addReply(c,emptyreply);
1356 return;
1357 }
1358
1359 /* We don't know in advance how many matching elements there are in the
1360 * list, so we push this object that will represent the multi-bulk length
1361 * in the output buffer, and will "fix" it later */
1362 if (!justcount)
1363 replylen = addDeferredMultiBulkLength(c);
1364
1365 /* If there is an offset, just traverse the number of elements without
1366 * checking the score because that is done in the next loop. */
1367 while(ln && offset--) {
1368 ln = reverse ? ln->backward : ln->level[0].forward;
1369 }
1370
1371 while (ln && limit--) {
1372 /* Abort when the node is no longer in range. */
1373 if (reverse) {
1374 if (!zslValueGteMin(ln->score,&range)) break;
1375 } else {
1376 if (!zslValueLteMax(ln->score,&range)) break;
1377 }
1378
1379 /* Do our magic */
1380 rangelen++;
1381 if (!justcount) {
1382 addReplyBulk(c,ln->obj);
1383 if (withscores)
1384 addReplyDouble(c,ln->score);
1385 }
1386
1387 /* Move to next node */
1388 ln = reverse ? ln->backward : ln->level[0].forward;
1389 }
1390
1391 if (justcount) {
1392 addReplyLongLong(c,(long)rangelen);
1393 } else {
1394 setDeferredMultiBulkLength(c,replylen,
1395 withscores ? (rangelen*2) : rangelen);
1396 }
1397 }
1398
1399 void zrangebyscoreCommand(redisClient *c) {
1400 genericZrangebyscoreCommand(c,0,0);
1401 }
1402
1403 void zrevrangebyscoreCommand(redisClient *c) {
1404 genericZrangebyscoreCommand(c,1,0);
1405 }
1406
1407 void zcountCommand(redisClient *c) {
1408 genericZrangebyscoreCommand(c,0,1);
1409 }
1410
1411 void zcardCommand(redisClient *c) {
1412 robj *o;
1413 zset *zs;
1414
1415 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
1416 checkType(c,o,REDIS_ZSET)) return;
1417
1418 zs = o->ptr;
1419 addReplyLongLong(c,zs->zsl->length);
1420 }
1421
1422 void zscoreCommand(redisClient *c) {
1423 robj *o;
1424 zset *zs;
1425 dictEntry *de;
1426
1427 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
1428 checkType(c,o,REDIS_ZSET)) return;
1429
1430 zs = o->ptr;
1431 c->argv[2] = tryObjectEncoding(c->argv[2]);
1432 de = dictFind(zs->dict,c->argv[2]);
1433 if (!de) {
1434 addReply(c,shared.nullbulk);
1435 } else {
1436 double *score = dictGetEntryVal(de);
1437
1438 addReplyDouble(c,*score);
1439 }
1440 }
1441
1442 void zrankGenericCommand(redisClient *c, int reverse) {
1443 robj *o;
1444 zset *zs;
1445 zskiplist *zsl;
1446 dictEntry *de;
1447 unsigned long rank;
1448 double *score;
1449
1450 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
1451 checkType(c,o,REDIS_ZSET)) return;
1452
1453 zs = o->ptr;
1454 zsl = zs->zsl;
1455 c->argv[2] = tryObjectEncoding(c->argv[2]);
1456 de = dictFind(zs->dict,c->argv[2]);
1457 if (!de) {
1458 addReply(c,shared.nullbulk);
1459 return;
1460 }
1461
1462 score = dictGetEntryVal(de);
1463 rank = zslGetRank(zsl, *score, c->argv[2]);
1464 if (rank) {
1465 if (reverse) {
1466 addReplyLongLong(c, zsl->length - rank);
1467 } else {
1468 addReplyLongLong(c, rank-1);
1469 }
1470 } else {
1471 addReply(c,shared.nullbulk);
1472 }
1473 }
1474
1475 void zrankCommand(redisClient *c) {
1476 zrankGenericCommand(c, 0);
1477 }
1478
1479 void zrevrankCommand(redisClient *c) {
1480 zrankGenericCommand(c, 1);
1481 }