]> git.saurik.com Git - redis.git/blame - src/t_zset.c
Fix DEBUG DIGEST, SORT and AOF rewrite
[redis.git] / src / t_zset.c
CommitLineData
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
26zskiplistNode *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
33zskiplist *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
50void zslFreeNode(zskiplistNode *node) {
51 decrRefCount(node->obj);
e2641e09 52 zfree(node);
53}
54
55void 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
67int 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 74zskiplistNode *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 */
130void 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. */
151int 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. */
178typedef struct {
179 double min, max;
180 int minex, maxex; /* are min or max exclusive? */
181} zrangespec;
182
45290ad9 183static int zslValueGteMin(double value, zrangespec *spec) {
22b9bf15
PN
184 return spec->minex ? (value > spec->min) : (value >= spec->min);
185}
186
45290ad9 187static int zslValueLteMax(double value, zrangespec *spec) {
22b9bf15
PN
188 return spec->maxex ? (value < spec->max) : (value <= spec->max);
189}
190
22b9bf15
PN
191/* Returns if there is a part of the zset is in range. */
192int zslIsInRange(zskiplist *zsl, zrangespec *range) {
193 zskiplistNode *x;
194
8e1b3277
PN
195 /* Test for ranges that will always be empty. */
196 if (range->min > range->max ||
197 (range->min == range->max && (range->minex || range->maxex)))
198 return 0;
22b9bf15 199 x = zsl->tail;
45290ad9 200 if (x == NULL || !zslValueGteMin(x->score,range))
22b9bf15
PN
201 return 0;
202 x = zsl->header->level[0].forward;
45290ad9 203 if (x == NULL || !zslValueLteMax(x->score,range))
22b9bf15
PN
204 return 0;
205 return 1;
206}
207
208/* Find the first node that is contained in the specified range.
209 * Returns NULL when no element is contained in the range. */
210zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec range) {
211 zskiplistNode *x;
212 int i;
213
214 /* If everything is out of range, return early. */
215 if (!zslIsInRange(zsl,&range)) return NULL;
216
217 x = zsl->header;
218 for (i = zsl->level-1; i >= 0; i--) {
219 /* Go forward while *OUT* of range. */
220 while (x->level[i].forward &&
45290ad9 221 !zslValueGteMin(x->level[i].forward->score,&range))
22b9bf15
PN
222 x = x->level[i].forward;
223 }
224
e53ca04b 225 /* This is an inner range, so the next node cannot be NULL. */
22b9bf15 226 x = x->level[0].forward;
e53ca04b
PN
227 redisAssert(x != NULL);
228
229 /* Check if score <= max. */
230 if (!zslValueLteMax(x->score,&range)) return NULL;
22b9bf15
PN
231 return x;
232}
233
234/* Find the last node that is contained in the specified range.
235 * Returns NULL when no element is contained in the range. */
236zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec range) {
237 zskiplistNode *x;
238 int i;
239
240 /* If everything is out of range, return early. */
241 if (!zslIsInRange(zsl,&range)) return NULL;
242
243 x = zsl->header;
244 for (i = zsl->level-1; i >= 0; i--) {
245 /* Go forward while *IN* range. */
246 while (x->level[i].forward &&
45290ad9 247 zslValueLteMax(x->level[i].forward->score,&range))
22b9bf15
PN
248 x = x->level[i].forward;
249 }
250
e53ca04b
PN
251 /* This is an inner range, so this node cannot be NULL. */
252 redisAssert(x != NULL);
253
254 /* Check if score >= min. */
255 if (!zslValueGteMin(x->score,&range)) return NULL;
22b9bf15
PN
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 263unsigned 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 */
294unsigned 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 326unsigned 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 350zskiplistNode* 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
370static 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
410double 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. */
432int 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
bbfe232f 452unsigned int zzlLength(unsigned char *zl) {
0b10e104
PN
453 return ziplistLen(zl)/2;
454}
455
4c5f0966
PN
456/* Move to next entry based on the values in eptr and sptr. Both are set to
457 * NULL when there is no next entry. */
458void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
459 unsigned char *_eptr, *_sptr;
460 redisAssert(*eptr != NULL && *sptr != NULL);
461
462 _eptr = ziplistNext(zl,*sptr);
463 if (_eptr != NULL) {
464 _sptr = ziplistNext(zl,_eptr);
465 redisAssert(_sptr != NULL);
466 } else {
467 /* No next entry. */
468 _sptr = NULL;
469 }
470
471 *eptr = _eptr;
472 *sptr = _sptr;
473}
474
475/* Move to the previous entry based on the values in eptr and sptr. Both are
476 * set to NULL when there is no next entry. */
477void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
478 unsigned char *_eptr, *_sptr;
479 redisAssert(*eptr != NULL && *sptr != NULL);
480
481 _sptr = ziplistPrev(zl,*eptr);
482 if (_sptr != NULL) {
483 _eptr = ziplistPrev(zl,_sptr);
484 redisAssert(_eptr != NULL);
485 } else {
486 /* No previous entry. */
487 _eptr = NULL;
488 }
489
490 *eptr = _eptr;
491 *sptr = _sptr;
492}
493
4a14dbba
PN
494/* Returns if there is a part of the zset is in range. Should only be used
495 * internally by zzlFirstInRange and zzlLastInRange. */
496int zzlIsInRange(unsigned char *zl, zrangespec *range) {
497 unsigned char *p;
498 double score;
499
500 /* Test for ranges that will always be empty. */
501 if (range->min > range->max ||
502 (range->min == range->max && (range->minex || range->maxex)))
503 return 0;
504
505 p = ziplistIndex(zl,-1); /* Last score. */
506 redisAssert(p != NULL);
507 score = zzlGetScore(p);
508 if (!zslValueGteMin(score,range))
509 return 0;
510
511 p = ziplistIndex(zl,1); /* First score. */
512 redisAssert(p != NULL);
513 score = zzlGetScore(p);
514 if (!zslValueLteMax(score,range))
515 return 0;
516
517 return 1;
518}
519
520/* Find pointer to the first element contained in the specified range.
521 * Returns NULL when no element is contained in the range. */
8588bfa3 522unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec range) {
4a14dbba
PN
523 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
524 double score;
525
526 /* If everything is out of range, return early. */
527 if (!zzlIsInRange(zl,&range)) return NULL;
528
529 while (eptr != NULL) {
530 sptr = ziplistNext(zl,eptr);
531 redisAssert(sptr != NULL);
532
533 score = zzlGetScore(sptr);
e53ca04b
PN
534 if (zslValueGteMin(score,&range)) {
535 /* Check if score <= max. */
536 if (zslValueLteMax(score,&range))
537 return eptr;
538 return NULL;
539 }
4a14dbba
PN
540
541 /* Move to next element. */
542 eptr = ziplistNext(zl,sptr);
543 }
544
545 return NULL;
546}
547
548/* Find pointer to the last element contained in the specified range.
549 * Returns NULL when no element is contained in the range. */
8588bfa3 550unsigned char *zzlLastInRange(unsigned char *zl, zrangespec range) {
4a14dbba
PN
551 unsigned char *eptr = ziplistIndex(zl,-2), *sptr;
552 double score;
553
554 /* If everything is out of range, return early. */
555 if (!zzlIsInRange(zl,&range)) return NULL;
556
557 while (eptr != NULL) {
558 sptr = ziplistNext(zl,eptr);
559 redisAssert(sptr != NULL);
560
561 score = zzlGetScore(sptr);
e53ca04b
PN
562 if (zslValueLteMax(score,&range)) {
563 /* Check if score >= min. */
564 if (zslValueGteMin(score,&range))
565 return eptr;
566 return NULL;
567 }
4a14dbba
PN
568
569 /* Move to previous element by moving to the score of previous element.
570 * When this returns NULL, we know there also is no element. */
571 sptr = ziplistPrev(zl,eptr);
572 if (sptr != NULL)
573 redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
574 else
575 eptr = NULL;
576 }
577
578 return NULL;
579}
580
8588bfa3 581unsigned char *zzlFind(unsigned char *zl, robj *ele, double *score) {
21c5b508
PN
582 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
583
584 ele = getDecodedObject(ele);
585 while (eptr != NULL) {
586 sptr = ziplistNext(zl,eptr);
587 redisAssert(sptr != NULL);
588
589 if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) {
590 /* Matching element, pull out score. */
0b10e104 591 if (score != NULL) *score = zzlGetScore(sptr);
21c5b508
PN
592 decrRefCount(ele);
593 return eptr;
594 }
595
596 /* Move to next element. */
597 eptr = ziplistNext(zl,sptr);
598 }
599
600 decrRefCount(ele);
601 return NULL;
602}
603
604/* Delete (element,score) pair from ziplist. Use local copy of eptr because we
605 * don't want to modify the one given as argument. */
8588bfa3 606unsigned char *zzlDelete(unsigned char *zl, unsigned char *eptr) {
21c5b508
PN
607 unsigned char *p = eptr;
608
609 /* TODO: add function to ziplist API to delete N elements from offset. */
610 zl = ziplistDelete(zl,&p);
611 zl = ziplistDelete(zl,&p);
8588bfa3 612 return zl;
21c5b508
PN
613}
614
8588bfa3 615unsigned char *zzlInsertAt(unsigned char *zl, unsigned char *eptr, robj *ele, double score) {
21c5b508
PN
616 unsigned char *sptr;
617 char scorebuf[128];
618 int scorelen;
69298a05 619 size_t offset;
21c5b508
PN
620
621 redisAssert(ele->encoding == REDIS_ENCODING_RAW);
622 scorelen = d2string(scorebuf,sizeof(scorebuf),score);
623 if (eptr == NULL) {
624 zl = ziplistPush(zl,ele->ptr,sdslen(ele->ptr),ZIPLIST_TAIL);
625 zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL);
626 } else {
627 /* Keep offset relative to zl, as it might be re-allocated. */
628 offset = eptr-zl;
629 zl = ziplistInsert(zl,eptr,ele->ptr,sdslen(ele->ptr));
630 eptr = zl+offset;
631
632 /* Insert score after the element. */
633 redisAssert((sptr = ziplistNext(zl,eptr)) != NULL);
634 zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen);
635 }
636
8588bfa3 637 return zl;
21c5b508
PN
638}
639
640/* Insert (element,score) pair in ziplist. This function assumes the element is
641 * not yet present in the list. */
8588bfa3 642unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score) {
21c5b508
PN
643 unsigned char *eptr = ziplistIndex(zl,0), *sptr;
644 double s;
21c5b508
PN
645
646 ele = getDecodedObject(ele);
647 while (eptr != NULL) {
648 sptr = ziplistNext(zl,eptr);
649 redisAssert(sptr != NULL);
650 s = zzlGetScore(sptr);
651
652 if (s > score) {
653 /* First element with score larger than score for element to be
654 * inserted. This means we should take its spot in the list to
655 * maintain ordering. */
8588bfa3 656 zl = zzlInsertAt(zl,eptr,ele,score);
21c5b508 657 break;
8218db3d
PN
658 } else if (s == score) {
659 /* Ensure lexicographical ordering for elements. */
d1c920c5 660 if (zzlCompareElements(eptr,ele->ptr,sdslen(ele->ptr)) > 0) {
8588bfa3 661 zl = zzlInsertAt(zl,eptr,ele,score);
8218db3d
PN
662 break;
663 }
21c5b508
PN
664 }
665
666 /* Move to next element. */
667 eptr = ziplistNext(zl,sptr);
668 }
669
670 /* Push on tail of list when it was not yet inserted. */
8218db3d 671 if (eptr == NULL)
8588bfa3 672 zl = zzlInsertAt(zl,NULL,ele,score);
21c5b508
PN
673
674 decrRefCount(ele);
8588bfa3 675 return zl;
21c5b508 676}
25bb8a44 677
8588bfa3 678unsigned char *zzlDeleteRangeByScore(unsigned char *zl, zrangespec range, unsigned long *deleted) {
4a14dbba
PN
679 unsigned char *eptr, *sptr;
680 double score;
8588bfa3 681 unsigned long num = 0;
4a14dbba 682
8588bfa3 683 if (deleted != NULL) *deleted = 0;
4a14dbba 684
8588bfa3
PN
685 eptr = zzlFirstInRange(zl,range);
686 if (eptr == NULL) return zl;
4a14dbba
PN
687
688 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
689 * byte and ziplistNext will return NULL. */
690 while ((sptr = ziplistNext(zl,eptr)) != NULL) {
691 score = zzlGetScore(sptr);
692 if (zslValueLteMax(score,&range)) {
693 /* Delete both the element and the score. */
694 zl = ziplistDelete(zl,&eptr);
695 zl = ziplistDelete(zl,&eptr);
8588bfa3 696 num++;
4a14dbba
PN
697 } else {
698 /* No longer in range. */
699 break;
700 }
701 }
702
8588bfa3
PN
703 if (deleted != NULL) *deleted = num;
704 return zl;
4a14dbba
PN
705}
706
63b7b7fb
PN
707/* Delete all the elements with rank between start and end from the skiplist.
708 * Start and end are inclusive. Note that start and end need to be 1-based */
8588bfa3 709unsigned char *zzlDeleteRangeByRank(unsigned char *zl, unsigned int start, unsigned int end, unsigned long *deleted) {
63b7b7fb 710 unsigned int num = (end-start)+1;
8588bfa3
PN
711 if (deleted) *deleted = num;
712 zl = ziplistDeleteRange(zl,2*(start-1),2*num);
713 return zl;
63b7b7fb
PN
714}
715
5d1b4fb6
PN
716/*-----------------------------------------------------------------------------
717 * Common sorted set API
718 *----------------------------------------------------------------------------*/
719
df26a0ae 720unsigned int zsetLength(robj *zobj) {
5d1b4fb6
PN
721 int length = -1;
722 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
bbfe232f 723 length = zzlLength(zobj->ptr);
5d1b4fb6
PN
724 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
725 length = ((zset*)zobj->ptr)->zsl->length;
726 } else {
727 redisPanic("Unknown sorted set encoding");
728 }
729 return length;
730}
731
df26a0ae 732void zsetConvert(robj *zobj, int encoding) {
a669d5e9
PN
733 zset *zs;
734 zskiplistNode *node, *next;
735 robj *ele;
736 double score;
737
738 if (zobj->encoding == encoding) return;
739 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
740 unsigned char *zl = zobj->ptr;
741 unsigned char *eptr, *sptr;
742 unsigned char *vstr;
743 unsigned int vlen;
744 long long vlong;
745
746 if (encoding != REDIS_ENCODING_RAW)
747 redisPanic("Unknown target encoding");
748
749 zs = zmalloc(sizeof(*zs));
750 zs->dict = dictCreate(&zsetDictType,NULL);
751 zs->zsl = zslCreate();
752
753 eptr = ziplistIndex(zl,0);
754 redisAssert(eptr != NULL);
755 sptr = ziplistNext(zl,eptr);
756 redisAssert(sptr != NULL);
757
758 while (eptr != NULL) {
759 score = zzlGetScore(sptr);
760 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
761 if (vstr == NULL)
762 ele = createStringObjectFromLongLong(vlong);
763 else
764 ele = createStringObject((char*)vstr,vlen);
765
766 /* Has incremented refcount since it was just created. */
767 node = zslInsert(zs->zsl,score,ele);
768 redisAssert(dictAdd(zs->dict,ele,&node->score) == DICT_OK);
769 incrRefCount(ele); /* Added to dictionary. */
770 zzlNext(zl,&eptr,&sptr);
771 }
772
773 zfree(zobj->ptr);
774 zobj->ptr = zs;
775 zobj->encoding = REDIS_ENCODING_RAW;
776 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
777 unsigned char *zl = ziplistNew();
778
779 if (encoding != REDIS_ENCODING_ZIPLIST)
780 redisPanic("Unknown target encoding");
781
782 /* Approach similar to zslFree(), since we want to free the skiplist at
783 * the same time as creating the ziplist. */
784 zs = zobj->ptr;
785 dictRelease(zs->dict);
786 node = zs->zsl->header->level[0].forward;
787 zfree(zs->zsl->header);
788 zfree(zs->zsl);
789
a669d5e9
PN
790 while (node) {
791 ele = getDecodedObject(node->obj);
8588bfa3 792 zl = zzlInsertAt(zl,NULL,ele,node->score);
a669d5e9
PN
793 decrRefCount(ele);
794
795 next = node->level[0].forward;
796 zslFreeNode(node);
797 node = next;
798 }
799
800 zfree(zs);
8588bfa3 801 zobj->ptr = zl;
a669d5e9
PN
802 zobj->encoding = REDIS_ENCODING_ZIPLIST;
803 } else {
804 redisPanic("Unknown sorted set encoding");
805 }
806}
807
e2641e09 808/*-----------------------------------------------------------------------------
809 * Sorted set commands
810 *----------------------------------------------------------------------------*/
811
69ef89f2 812/* This generic command implements both ZADD and ZINCRBY. */
3ca7532a 813void zaddGenericCommand(redisClient *c, int incr) {
21c5b508 814 static char *nanerr = "resulting score is not a number (NaN)";
3ca7532a
PN
815 robj *key = c->argv[1];
816 robj *ele;
21c5b508
PN
817 robj *zobj;
818 robj *curobj;
3ca7532a
PN
819 double score, curscore = 0.0;
820
821 if (getDoubleFromObjectOrReply(c,c->argv[2],&score,NULL) != REDIS_OK)
822 return;
21c5b508
PN
823
824 zobj = lookupKeyWrite(c->db,key);
825 if (zobj == NULL) {
a669d5e9
PN
826 if (server.zset_max_ziplist_entries == 0 ||
827 server.zset_max_ziplist_value < sdslen(c->argv[3]->ptr))
828 {
829 zobj = createZsetObject();
830 } else {
831 zobj = createZsetZiplistObject();
832 }
21c5b508 833 dbAdd(c->db,key,zobj);
e2641e09 834 } else {
21c5b508 835 if (zobj->type != REDIS_ZSET) {
e2641e09 836 addReply(c,shared.wrongtypeerr);
837 return;
838 }
839 }
e2641e09 840
21c5b508
PN
841 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
842 unsigned char *eptr;
843
3ca7532a
PN
844 /* Prefer non-encoded element when dealing with ziplists. */
845 ele = c->argv[3];
8588bfa3 846 if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
21c5b508
PN
847 if (incr) {
848 score += curscore;
849 if (isnan(score)) {
850 addReplyError(c,nanerr);
851 /* Don't need to check if the sorted set is empty, because
852 * we know it has at least one element. */
853 return;
854 }
855 }
856
857 /* Remove and re-insert when score changed. */
858 if (score != curscore) {
8588bfa3
PN
859 zobj->ptr = zzlDelete(zobj->ptr,eptr);
860 zobj->ptr = zzlInsert(zobj->ptr,ele,score);
21c5b508
PN
861
862 signalModifiedKey(c->db,key);
863 server.dirty++;
864 }
865
866 if (incr) /* ZINCRBY */
867 addReplyDouble(c,score);
868 else /* ZADD */
869 addReply(c,shared.czero);
870 } else {
a669d5e9
PN
871 /* Optimize: check if the element is too large or the list becomes
872 * too long *before* executing zzlInsert. */
8588bfa3 873 zobj->ptr = zzlInsert(zobj->ptr,ele,score);
bbfe232f 874 if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries)
df26a0ae 875 zsetConvert(zobj,REDIS_ENCODING_RAW);
a669d5e9 876 if (sdslen(ele->ptr) > server.zset_max_ziplist_value)
df26a0ae 877 zsetConvert(zobj,REDIS_ENCODING_RAW);
69ef89f2 878
21c5b508
PN
879 signalModifiedKey(c->db,key);
880 server.dirty++;
69ef89f2 881
21c5b508
PN
882 if (incr) /* ZINCRBY */
883 addReplyDouble(c,score);
884 else /* ZADD */
885 addReply(c,shared.cone);
886 }
887 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
888 zset *zs = zobj->ptr;
889 zskiplistNode *znode;
e2641e09 890 dictEntry *de;
e2641e09 891
3ca7532a 892 ele = c->argv[3] = tryObjectEncoding(c->argv[3]);
e2641e09 893 de = dictFind(zs->dict,ele);
21c5b508
PN
894 if (de != NULL) {
895 curobj = dictGetEntryKey(de);
896 curscore = *(double*)dictGetEntryVal(de);
897
898 if (incr) {
899 score += curscore;
900 if (isnan(score)) {
901 addReplyError(c,nanerr);
902 /* Don't need to check if the sorted set is empty, because
903 * we know it has at least one element. */
904 return;
905 }
906 }
907
908 /* Remove and re-insert when score changed. We can safely delete
909 * the key object from the skiplist, since the dictionary still has
910 * a reference to it. */
911 if (score != curscore) {
912 redisAssert(zslDelete(zs->zsl,curscore,curobj));
913 znode = zslInsert(zs->zsl,score,curobj);
914 incrRefCount(curobj); /* Re-inserted in skiplist. */
915 dictGetEntryVal(de) = &znode->score; /* Update score ptr. */
916
917 signalModifiedKey(c->db,key);
918 server.dirty++;
919 }
920
921 if (incr) /* ZINCRBY */
922 addReplyDouble(c,score);
923 else /* ZADD */
924 addReply(c,shared.czero);
925 } else {
926 znode = zslInsert(zs->zsl,score,ele);
927 incrRefCount(ele); /* Inserted in skiplist. */
928 redisAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
929 incrRefCount(ele); /* Added to dictionary. */
930
931 signalModifiedKey(c->db,key);
e2641e09 932 server.dirty++;
21c5b508
PN
933
934 if (incr) /* ZINCRBY */
935 addReplyDouble(c,score);
936 else /* ZADD */
937 addReply(c,shared.cone);
e2641e09 938 }
21c5b508
PN
939 } else {
940 redisPanic("Unknown sorted set encoding");
e2641e09 941 }
942}
943
944void zaddCommand(redisClient *c) {
3ca7532a 945 zaddGenericCommand(c,0);
e2641e09 946}
947
948void zincrbyCommand(redisClient *c) {
3ca7532a 949 zaddGenericCommand(c,1);
e2641e09 950}
951
952void zremCommand(redisClient *c) {
0b10e104
PN
953 robj *key = c->argv[1];
954 robj *ele = c->argv[2];
955 robj *zobj;
956
957 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
958 checkType(c,zobj,REDIS_ZSET)) return;
959
960 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
961 unsigned char *eptr;
962
8588bfa3
PN
963 if ((eptr = zzlFind(zobj->ptr,ele,NULL)) != NULL) {
964 zobj->ptr = zzlDelete(zobj->ptr,eptr);
bbfe232f 965 if (zzlLength(zobj->ptr) == 0) dbDelete(c->db,key);
0b10e104
PN
966 } else {
967 addReply(c,shared.czero);
968 return;
969 }
970 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
971 zset *zs = zobj->ptr;
972 dictEntry *de;
973 double score;
974
975 de = dictFind(zs->dict,ele);
976 if (de != NULL) {
977 /* Delete from the skiplist */
978 score = *(double*)dictGetEntryVal(de);
979 redisAssert(zslDelete(zs->zsl,score,ele));
980
981 /* Delete from the hash table */
982 dictDelete(zs->dict,ele);
983 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
984 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
985 } else {
986 addReply(c,shared.czero);
987 return;
988 }
989 } else {
990 redisPanic("Unknown sorted set encoding");
e2641e09 991 }
e2641e09 992
0b10e104 993 signalModifiedKey(c->db,key);
e2641e09 994 server.dirty++;
995 addReply(c,shared.cone);
996}
997
998void zremrangebyscoreCommand(redisClient *c) {
4a14dbba
PN
999 robj *key = c->argv[1];
1000 robj *zobj;
91504b6c 1001 zrangespec range;
4a14dbba 1002 unsigned long deleted;
e2641e09 1003
91504b6c 1004 /* Parse the range arguments. */
7236fdb2
PN
1005 if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
1006 addReplyError(c,"min or max is not a double");
1007 return;
1008 }
e2641e09 1009
4a14dbba
PN
1010 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1011 checkType(c,zobj,REDIS_ZSET)) return;
1012
1013 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
8588bfa3 1014 zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,range,&deleted);
4a14dbba
PN
1015 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1016 zset *zs = zobj->ptr;
1017 deleted = zslDeleteRangeByScore(zs->zsl,range,zs->dict);
1018 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1019 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
1020 } else {
1021 redisPanic("Unknown sorted set encoding");
1022 }
e2641e09 1023
4a14dbba 1024 if (deleted) signalModifiedKey(c->db,key);
e2641e09 1025 server.dirty += deleted;
1026 addReplyLongLong(c,deleted);
1027}
1028
1029void zremrangebyrankCommand(redisClient *c) {
63b7b7fb
PN
1030 robj *key = c->argv[1];
1031 robj *zobj;
e2641e09 1032 long start;
1033 long end;
1034 int llen;
63b7b7fb 1035 unsigned long deleted;
e2641e09 1036
1037 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
1038 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
1039
63b7b7fb
PN
1040 if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1041 checkType(c,zobj,REDIS_ZSET)) return;
e2641e09 1042
63b7b7fb 1043 /* Sanitize indexes. */
df26a0ae 1044 llen = zsetLength(zobj);
e2641e09 1045 if (start < 0) start = llen+start;
1046 if (end < 0) end = llen+end;
1047 if (start < 0) start = 0;
e2641e09 1048
d0a4e24e
PN
1049 /* Invariant: start >= 0, so this test will be true when end < 0.
1050 * The range is empty when start > end or start >= length. */
e2641e09 1051 if (start > end || start >= llen) {
1052 addReply(c,shared.czero);
1053 return;
1054 }
1055 if (end >= llen) end = llen-1;
1056
63b7b7fb
PN
1057 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1058 /* Correct for 1-based rank. */
8588bfa3 1059 zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted);
63b7b7fb
PN
1060 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1061 zset *zs = zobj->ptr;
1062
1063 /* Correct for 1-based rank. */
1064 deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
1065 if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1066 if (dictSize(zs->dict) == 0) dbDelete(c->db,key);
1067 } else {
1068 redisPanic("Unknown sorted set encoding");
1069 }
1070
1071 if (deleted) signalModifiedKey(c->db,key);
e2641e09 1072 server.dirty += deleted;
63b7b7fb 1073 addReplyLongLong(c,deleted);
e2641e09 1074}
1075
1076typedef struct {
56ce42fa
PN
1077 robj *subject;
1078 int type; /* Set, sorted set */
1079 int encoding;
e2641e09 1080 double weight;
56ce42fa
PN
1081
1082 union {
1083 /* Set iterators. */
1084 union _iterset {
1085 struct {
1086 intset *is;
1087 int ii;
1088 } is;
1089 struct {
1090 dict *dict;
1091 dictIterator *di;
1092 dictEntry *de;
1093 } ht;
1094 } set;
1095
1096 /* Sorted set iterators. */
1097 union _iterzset {
1098 struct {
1099 unsigned char *zl;
1100 unsigned char *eptr, *sptr;
1101 } zl;
1102 struct {
1103 zset *zs;
1104 zskiplistNode *node;
1105 } sl;
1106 } zset;
1107 } iter;
e2641e09 1108} zsetopsrc;
1109
56ce42fa
PN
1110
1111/* Use dirty flags for pointers that need to be cleaned up in the next
1112 * iteration over the zsetopval. The dirty flag for the long long value is
1113 * special, since long long values don't need cleanup. Instead, it means that
1114 * we already checked that "ell" holds a long long, or tried to convert another
1115 * representation into a long long value. When this was successful,
1116 * OPVAL_VALID_LL is set as well. */
1117#define OPVAL_DIRTY_ROBJ 1
1118#define OPVAL_DIRTY_LL 2
1119#define OPVAL_VALID_LL 4
1120
1121/* Store value retrieved from the iterator. */
1122typedef struct {
1123 int flags;
1124 unsigned char _buf[32]; /* Private buffer. */
1125 robj *ele;
1126 unsigned char *estr;
1127 unsigned int elen;
1128 long long ell;
1129 double score;
1130} zsetopval;
1131
1132typedef union _iterset iterset;
1133typedef union _iterzset iterzset;
1134
1135void zuiInitIterator(zsetopsrc *op) {
1136 if (op->subject == NULL)
1137 return;
1138
1139 if (op->type == REDIS_SET) {
1140 iterset *it = &op->iter.set;
1141 if (op->encoding == REDIS_ENCODING_INTSET) {
1142 it->is.is = op->subject->ptr;
1143 it->is.ii = 0;
1144 } else if (op->encoding == REDIS_ENCODING_HT) {
1145 it->ht.dict = op->subject->ptr;
1146 it->ht.di = dictGetIterator(op->subject->ptr);
1147 it->ht.de = dictNext(it->ht.di);
1148 } else {
1149 redisPanic("Unknown set encoding");
1150 }
1151 } else if (op->type == REDIS_ZSET) {
1152 iterzset *it = &op->iter.zset;
1153 if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1154 it->zl.zl = op->subject->ptr;
1155 it->zl.eptr = ziplistIndex(it->zl.zl,0);
1156 if (it->zl.eptr != NULL) {
1157 it->zl.sptr = ziplistNext(it->zl.zl,it->zl.eptr);
1158 redisAssert(it->zl.sptr != NULL);
1159 }
1160 } else if (op->encoding == REDIS_ENCODING_RAW) {
1161 it->sl.zs = op->subject->ptr;
1162 it->sl.node = it->sl.zs->zsl->header->level[0].forward;
1163 } else {
1164 redisPanic("Unknown sorted set encoding");
1165 }
1166 } else {
1167 redisPanic("Unsupported type");
1168 }
1169}
1170
1171void zuiClearIterator(zsetopsrc *op) {
1172 if (op->subject == NULL)
1173 return;
1174
1175 if (op->type == REDIS_SET) {
1176 iterset *it = &op->iter.set;
1177 if (op->encoding == REDIS_ENCODING_INTSET) {
1178 REDIS_NOTUSED(it); /* skip */
1179 } else if (op->encoding == REDIS_ENCODING_HT) {
1180 dictReleaseIterator(it->ht.di);
1181 } else {
1182 redisPanic("Unknown set encoding");
1183 }
1184 } else if (op->type == REDIS_ZSET) {
1185 iterzset *it = &op->iter.zset;
1186 if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1187 REDIS_NOTUSED(it); /* skip */
1188 } else if (op->encoding == REDIS_ENCODING_RAW) {
1189 REDIS_NOTUSED(it); /* skip */
1190 } else {
1191 redisPanic("Unknown sorted set encoding");
1192 }
1193 } else {
1194 redisPanic("Unsupported type");
1195 }
1196}
1197
1198int zuiLength(zsetopsrc *op) {
1199 if (op->subject == NULL)
1200 return 0;
1201
1202 if (op->type == REDIS_SET) {
1203 iterset *it = &op->iter.set;
1204 if (op->encoding == REDIS_ENCODING_INTSET) {
1205 return intsetLen(it->is.is);
1206 } else if (op->encoding == REDIS_ENCODING_HT) {
1207 return dictSize(it->ht.dict);
1208 } else {
1209 redisPanic("Unknown set encoding");
1210 }
1211 } else if (op->type == REDIS_ZSET) {
1212 iterzset *it = &op->iter.zset;
1213 if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1214 return zzlLength(it->zl.zl);
1215 } else if (op->encoding == REDIS_ENCODING_RAW) {
1216 return it->sl.zs->zsl->length;
1217 } else {
1218 redisPanic("Unknown sorted set encoding");
1219 }
1220 } else {
1221 redisPanic("Unsupported type");
1222 }
1223}
1224
1225/* Check if the current value is valid. If so, store it in the passed structure
1226 * and move to the next element. If not valid, this means we have reached the
1227 * end of the structure and can abort. */
1228int zuiNext(zsetopsrc *op, zsetopval *val) {
1229 if (op->subject == NULL)
1230 return 0;
1231
1232 if (val->flags & OPVAL_DIRTY_ROBJ)
1233 decrRefCount(val->ele);
1234
1235 bzero(val,sizeof(zsetopval));
1236
1237 if (op->type == REDIS_SET) {
1238 iterset *it = &op->iter.set;
1239 if (op->encoding == REDIS_ENCODING_INTSET) {
1240 if (!intsetGet(it->is.is,it->is.ii,&val->ell))
1241 return 0;
1242 val->score = 1.0;
1243
1244 /* Move to next element. */
1245 it->is.ii++;
1246 } else if (op->encoding == REDIS_ENCODING_HT) {
1247 if (it->ht.de == NULL)
1248 return 0;
1249 val->ele = dictGetEntryKey(it->ht.de);
1250 val->score = 1.0;
1251
1252 /* Move to next element. */
1253 it->ht.de = dictNext(it->ht.di);
1254 } else {
1255 redisPanic("Unknown set encoding");
1256 }
1257 } else if (op->type == REDIS_ZSET) {
1258 iterzset *it = &op->iter.zset;
1259 if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1260 /* No need to check both, but better be explicit. */
1261 if (it->zl.eptr == NULL || it->zl.sptr == NULL)
1262 return 0;
1263 redisAssert(ziplistGet(it->zl.eptr,&val->estr,&val->elen,&val->ell));
1264 val->score = zzlGetScore(it->zl.sptr);
1265
1266 /* Move to next element. */
1267 zzlNext(it->zl.zl,&it->zl.eptr,&it->zl.sptr);
1268 } else if (op->encoding == REDIS_ENCODING_RAW) {
1269 if (it->sl.node == NULL)
1270 return 0;
1271 val->ele = it->sl.node->obj;
1272 val->score = it->sl.node->score;
1273
1274 /* Move to next element. */
1275 it->sl.node = it->sl.node->level[0].forward;
1276 } else {
1277 redisPanic("Unknown sorted set encoding");
1278 }
1279 } else {
1280 redisPanic("Unsupported type");
1281 }
1282 return 1;
1283}
1284
1285int zuiLongLongFromValue(zsetopval *val) {
1286 if (!(val->flags & OPVAL_DIRTY_LL)) {
1287 val->flags |= OPVAL_DIRTY_LL;
1288
1289 if (val->ele != NULL) {
1290 if (val->ele->encoding == REDIS_ENCODING_INT) {
1291 val->ell = (long)val->ele->ptr;
1292 val->flags |= OPVAL_VALID_LL;
1293 } else if (val->ele->encoding == REDIS_ENCODING_RAW) {
1294 if (string2ll(val->ele->ptr,sdslen(val->ele->ptr),&val->ell))
1295 val->flags |= OPVAL_VALID_LL;
1296 } else {
1297 redisPanic("Unsupported element encoding");
1298 }
1299 } else if (val->estr != NULL) {
1300 if (string2ll((char*)val->estr,val->elen,&val->ell))
1301 val->flags |= OPVAL_VALID_LL;
1302 } else {
1303 /* The long long was already set, flag as valid. */
1304 val->flags |= OPVAL_VALID_LL;
1305 }
1306 }
1307 return val->flags & OPVAL_VALID_LL;
1308}
1309
1310robj *zuiObjectFromValue(zsetopval *val) {
1311 if (val->ele == NULL) {
1312 if (val->estr != NULL) {
1313 val->ele = createStringObject((char*)val->estr,val->elen);
1314 } else {
1315 val->ele = createStringObjectFromLongLong(val->ell);
1316 }
1317 val->flags |= OPVAL_DIRTY_ROBJ;
1318 }
1319 return val->ele;
1320}
1321
1322int zuiBufferFromValue(zsetopval *val) {
1323 if (val->estr == NULL) {
1324 if (val->ele != NULL) {
1325 if (val->ele->encoding == REDIS_ENCODING_INT) {
1326 val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),(long)val->ele->ptr);
1327 val->estr = val->_buf;
1328 } else if (val->ele->encoding == REDIS_ENCODING_RAW) {
1329 val->elen = sdslen(val->ele->ptr);
1330 val->estr = val->ele->ptr;
1331 } else {
1332 redisPanic("Unsupported element encoding");
1333 }
1334 } else {
1335 val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),val->ell);
1336 val->estr = val->_buf;
1337 }
1338 }
1339 return 1;
1340}
1341
1342/* Find value pointed to by val in the source pointer to by op. When found,
1343 * return 1 and store its score in target. Return 0 otherwise. */
1344int zuiFind(zsetopsrc *op, zsetopval *val, double *score) {
1345 if (op->subject == NULL)
1346 return 0;
1347
1348 if (op->type == REDIS_SET) {
1349 iterset *it = &op->iter.set;
1350
1351 if (op->encoding == REDIS_ENCODING_INTSET) {
1352 if (zuiLongLongFromValue(val) && intsetFind(it->is.is,val->ell)) {
1353 *score = 1.0;
1354 return 1;
1355 } else {
1356 return 0;
1357 }
1358 } else if (op->encoding == REDIS_ENCODING_HT) {
1359 zuiObjectFromValue(val);
1360 if (dictFind(it->ht.dict,val->ele) != NULL) {
1361 *score = 1.0;
1362 return 1;
1363 } else {
1364 return 0;
1365 }
1366 } else {
1367 redisPanic("Unknown set encoding");
1368 }
1369 } else if (op->type == REDIS_ZSET) {
1370 iterzset *it = &op->iter.zset;
1371 zuiObjectFromValue(val);
1372
1373 if (op->encoding == REDIS_ENCODING_ZIPLIST) {
8588bfa3 1374 if (zzlFind(it->zl.zl,val->ele,score) != NULL) {
56ce42fa
PN
1375 /* Score is already set by zzlFind. */
1376 return 1;
1377 } else {
1378 return 0;
1379 }
1380 } else if (op->encoding == REDIS_ENCODING_RAW) {
1381 dictEntry *de;
1382 if ((de = dictFind(it->sl.zs->dict,val->ele)) != NULL) {
1383 *score = *(double*)dictGetEntryVal(de);
1384 return 1;
1385 } else {
1386 return 0;
1387 }
1388 } else {
1389 redisPanic("Unknown sorted set encoding");
1390 }
1391 } else {
1392 redisPanic("Unsupported type");
1393 }
1394}
1395
1396int zuiCompareByCardinality(const void *s1, const void *s2) {
1397 return zuiLength((zsetopsrc*)s1) - zuiLength((zsetopsrc*)s2);
e2641e09 1398}
1399
1400#define REDIS_AGGR_SUM 1
1401#define REDIS_AGGR_MIN 2
1402#define REDIS_AGGR_MAX 3
1403#define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1404
1405inline static void zunionInterAggregate(double *target, double val, int aggregate) {
1406 if (aggregate == REDIS_AGGR_SUM) {
1407 *target = *target + val;
d9e28bcf
PN
1408 /* The result of adding two doubles is NaN when one variable
1409 * is +inf and the other is -inf. When these numbers are added,
1410 * we maintain the convention of the result being 0.0. */
1411 if (isnan(*target)) *target = 0.0;
e2641e09 1412 } else if (aggregate == REDIS_AGGR_MIN) {
1413 *target = val < *target ? val : *target;
1414 } else if (aggregate == REDIS_AGGR_MAX) {
1415 *target = val > *target ? val : *target;
1416 } else {
1417 /* safety net */
1418 redisPanic("Unknown ZUNION/INTER aggregate type");
1419 }
1420}
1421
1422void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
1423 int i, j, setnum;
1424 int aggregate = REDIS_AGGR_SUM;
1425 zsetopsrc *src;
56ce42fa
PN
1426 zsetopval zval;
1427 robj *tmp;
255eebe2 1428 unsigned int maxelelen = 0;
e2641e09 1429 robj *dstobj;
1430 zset *dstzset;
69ef89f2 1431 zskiplistNode *znode;
8c1420ff 1432 int touched = 0;
e2641e09 1433
1434 /* expect setnum input keys to be given */
1435 setnum = atoi(c->argv[2]->ptr);
1436 if (setnum < 1) {
3ab20376
PN
1437 addReplyError(c,
1438 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
e2641e09 1439 return;
1440 }
1441
1442 /* test if the expected number of keys would overflow */
1443 if (3+setnum > c->argc) {
1444 addReply(c,shared.syntaxerr);
1445 return;
1446 }
1447
1448 /* read keys to be used for input */
56ce42fa 1449 src = zcalloc(sizeof(zsetopsrc) * setnum);
e2641e09 1450 for (i = 0, j = 3; i < setnum; i++, j++) {
1451 robj *obj = lookupKeyWrite(c->db,c->argv[j]);
56ce42fa
PN
1452 if (obj != NULL) {
1453 if (obj->type != REDIS_ZSET && obj->type != REDIS_SET) {
e2641e09 1454 zfree(src);
1455 addReply(c,shared.wrongtypeerr);
1456 return;
1457 }
56ce42fa
PN
1458
1459 src[i].subject = obj;
1460 src[i].type = obj->type;
1461 src[i].encoding = obj->encoding;
1462 } else {
1463 src[i].subject = NULL;
e2641e09 1464 }
1465
56ce42fa 1466 /* Default all weights to 1. */
e2641e09 1467 src[i].weight = 1.0;
1468 }
1469
1470 /* parse optional extra arguments */
1471 if (j < c->argc) {
1472 int remaining = c->argc - j;
1473
1474 while (remaining) {
1475 if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
1476 j++; remaining--;
1477 for (i = 0; i < setnum; i++, j++, remaining--) {
673e1fb7
PN
1478 if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
1479 "weight value is not a double") != REDIS_OK)
1480 {
1481 zfree(src);
e2641e09 1482 return;
673e1fb7 1483 }
e2641e09 1484 }
1485 } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
1486 j++; remaining--;
1487 if (!strcasecmp(c->argv[j]->ptr,"sum")) {
1488 aggregate = REDIS_AGGR_SUM;
1489 } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
1490 aggregate = REDIS_AGGR_MIN;
1491 } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
1492 aggregate = REDIS_AGGR_MAX;
1493 } else {
1494 zfree(src);
1495 addReply(c,shared.syntaxerr);
1496 return;
1497 }
1498 j++; remaining--;
1499 } else {
1500 zfree(src);
1501 addReply(c,shared.syntaxerr);
1502 return;
1503 }
1504 }
1505 }
1506
56ce42fa
PN
1507 for (i = 0; i < setnum; i++)
1508 zuiInitIterator(&src[i]);
1509
e2641e09 1510 /* sort sets from the smallest to largest, this will improve our
1511 * algorithm's performance */
56ce42fa 1512 qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality);
e2641e09 1513
1514 dstobj = createZsetObject();
1515 dstzset = dstobj->ptr;
1516
1517 if (op == REDIS_OP_INTER) {
56ce42fa
PN
1518 /* Skip everything if the smallest input is empty. */
1519 if (zuiLength(&src[0]) > 0) {
1520 /* Precondition: as src[0] is non-empty and the inputs are ordered
1521 * by size, all src[i > 0] are non-empty too. */
1522 while (zuiNext(&src[0],&zval)) {
d433ebc6 1523 double score, value;
e2641e09 1524
56ce42fa 1525 score = src[0].weight * zval.score;
e2641e09 1526 for (j = 1; j < setnum; j++) {
56ce42fa
PN
1527 if (zuiFind(&src[j],&zval,&value)) {
1528 value *= src[j].weight;
d433ebc6 1529 zunionInterAggregate(&score,value,aggregate);
e2641e09 1530 } else {
1531 break;
1532 }
1533 }
1534
56ce42fa 1535 /* Only continue when present in every input. */
d433ebc6 1536 if (j == setnum) {
56ce42fa
PN
1537 tmp = zuiObjectFromValue(&zval);
1538 znode = zslInsert(dstzset->zsl,score,tmp);
1539 incrRefCount(tmp); /* added to skiplist */
1540 dictAdd(dstzset->dict,tmp,&znode->score);
1541 incrRefCount(tmp); /* added to dictionary */
255eebe2
PN
1542
1543 if (tmp->encoding == REDIS_ENCODING_RAW)
1544 if (sdslen(tmp->ptr) > maxelelen)
1545 maxelelen = sdslen(tmp->ptr);
e2641e09 1546 }
1547 }
e2641e09 1548 }
1549 } else if (op == REDIS_OP_UNION) {
1550 for (i = 0; i < setnum; i++) {
56ce42fa
PN
1551 if (zuiLength(&src[0]) == 0)
1552 continue;
e2641e09 1553
56ce42fa 1554 while (zuiNext(&src[i],&zval)) {
d433ebc6
PN
1555 double score, value;
1556
56ce42fa
PN
1557 /* Skip key when already processed */
1558 if (dictFind(dstzset->dict,zuiObjectFromValue(&zval)) != NULL)
d433ebc6 1559 continue;
e2641e09 1560
56ce42fa
PN
1561 /* Initialize score */
1562 score = src[i].weight * zval.score;
e2641e09 1563
56ce42fa
PN
1564 /* Because the inputs are sorted by size, it's only possible
1565 * for sets at larger indices to hold this element. */
e2641e09 1566 for (j = (i+1); j < setnum; j++) {
56ce42fa
PN
1567 if (zuiFind(&src[j],&zval,&value)) {
1568 value *= src[j].weight;
d433ebc6 1569 zunionInterAggregate(&score,value,aggregate);
e2641e09 1570 }
1571 }
1572
56ce42fa
PN
1573 tmp = zuiObjectFromValue(&zval);
1574 znode = zslInsert(dstzset->zsl,score,tmp);
1575 incrRefCount(zval.ele); /* added to skiplist */
1576 dictAdd(dstzset->dict,tmp,&znode->score);
1577 incrRefCount(zval.ele); /* added to dictionary */
255eebe2
PN
1578
1579 if (tmp->encoding == REDIS_ENCODING_RAW)
1580 if (sdslen(tmp->ptr) > maxelelen)
1581 maxelelen = sdslen(tmp->ptr);
e2641e09 1582 }
e2641e09 1583 }
1584 } else {
56ce42fa 1585 redisPanic("Unknown operator");
e2641e09 1586 }
1587
56ce42fa
PN
1588 for (i = 0; i < setnum; i++)
1589 zuiClearIterator(&src[i]);
1590
8c1420ff 1591 if (dbDelete(c->db,dstkey)) {
cea8c5cd 1592 signalModifiedKey(c->db,dstkey);
8c1420ff 1593 touched = 1;
1594 server.dirty++;
1595 }
e2641e09 1596 if (dstzset->zsl->length) {
255eebe2
PN
1597 /* Convert to ziplist when in limits. */
1598 if (dstzset->zsl->length <= server.zset_max_ziplist_entries &&
1599 maxelelen <= server.zset_max_ziplist_value)
df26a0ae 1600 zsetConvert(dstobj,REDIS_ENCODING_ZIPLIST);
255eebe2 1601
e2641e09 1602 dbAdd(c->db,dstkey,dstobj);
df26a0ae 1603 addReplyLongLong(c,zsetLength(dstobj));
cea8c5cd 1604 if (!touched) signalModifiedKey(c->db,dstkey);
cbf7e107 1605 server.dirty++;
e2641e09 1606 } else {
1607 decrRefCount(dstobj);
255eebe2 1608 addReply(c,shared.czero);
e2641e09 1609 }
1610 zfree(src);
1611}
1612
1613void zunionstoreCommand(redisClient *c) {
1614 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
1615}
1616
1617void zinterstoreCommand(redisClient *c) {
1618 zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
1619}
1620
1621void zrangeGenericCommand(redisClient *c, int reverse) {
5d1b4fb6
PN
1622 robj *key = c->argv[1];
1623 robj *zobj;
1624 int withscores = 0;
e2641e09 1625 long start;
1626 long end;
e2641e09 1627 int llen;
5d1b4fb6 1628 int rangelen;
e2641e09 1629
1630 if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
1631 (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
1632
1633 if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
1634 withscores = 1;
1635 } else if (c->argc >= 5) {
1636 addReply(c,shared.syntaxerr);
1637 return;
1638 }
1639
5d1b4fb6
PN
1640 if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
1641 || checkType(c,zobj,REDIS_ZSET)) return;
e2641e09 1642
5d1b4fb6 1643 /* Sanitize indexes. */
df26a0ae 1644 llen = zsetLength(zobj);
e2641e09 1645 if (start < 0) start = llen+start;
1646 if (end < 0) end = llen+end;
1647 if (start < 0) start = 0;
e2641e09 1648
d0a4e24e
PN
1649 /* Invariant: start >= 0, so this test will be true when end < 0.
1650 * The range is empty when start > end or start >= length. */
e2641e09 1651 if (start > end || start >= llen) {
e2641e09 1652 addReply(c,shared.emptymultibulk);
1653 return;
1654 }
1655 if (end >= llen) end = llen-1;
1656 rangelen = (end-start)+1;
1657
e2641e09 1658 /* Return the result in form of a multi-bulk reply */
5d1b4fb6
PN
1659 addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);
1660
1661 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1662 unsigned char *zl = zobj->ptr;
1663 unsigned char *eptr, *sptr;
1664 unsigned char *vstr;
1665 unsigned int vlen;
1666 long long vlong;
1667
1668 if (reverse)
1669 eptr = ziplistIndex(zl,-2-(2*start));
1670 else
1671 eptr = ziplistIndex(zl,2*start);
1672
4c5f0966
PN
1673 redisAssert(eptr != NULL);
1674 sptr = ziplistNext(zl,eptr);
1675
5d1b4fb6 1676 while (rangelen--) {
4c5f0966 1677 redisAssert(eptr != NULL && sptr != NULL);
5d1b4fb6
PN
1678 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
1679 if (vstr == NULL)
1680 addReplyBulkLongLong(c,vlong);
1681 else
1682 addReplyBulkCBuffer(c,vstr,vlen);
1683
4c5f0966 1684 if (withscores)
5d1b4fb6 1685 addReplyDouble(c,zzlGetScore(sptr));
5d1b4fb6 1686
4c5f0966
PN
1687 if (reverse)
1688 zzlPrev(zl,&eptr,&sptr);
1689 else
1690 zzlNext(zl,&eptr,&sptr);
5d1b4fb6
PN
1691 }
1692
1693 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1694 zset *zs = zobj->ptr;
1695 zskiplist *zsl = zs->zsl;
1696 zskiplistNode *ln;
1697 robj *ele;
1698
1699 /* Check if starting point is trivial, before doing log(N) lookup. */
1700 if (reverse) {
1701 ln = zsl->tail;
1702 if (start > 0)
1703 ln = zslGetElementByRank(zsl,llen-start);
1704 } else {
1705 ln = zsl->header->level[0].forward;
1706 if (start > 0)
1707 ln = zslGetElementByRank(zsl,start+1);
1708 }
1709
1710 while(rangelen--) {
1711 redisAssert(ln != NULL);
1712 ele = ln->obj;
1713 addReplyBulk(c,ele);
1714 if (withscores)
1715 addReplyDouble(c,ln->score);
1716 ln = reverse ? ln->backward : ln->level[0].forward;
1717 }
1718 } else {
1719 redisPanic("Unknown sorted set encoding");
e2641e09 1720 }
1721}
1722
1723void zrangeCommand(redisClient *c) {
1724 zrangeGenericCommand(c,0);
1725}
1726
1727void zrevrangeCommand(redisClient *c) {
1728 zrangeGenericCommand(c,1);
1729}
1730
25bb8a44
PN
1731/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1732 * If "justcount", only the number of elements in the range is returned. */
1733void genericZrangebyscoreCommand(redisClient *c, int reverse, int justcount) {
1734 zrangespec range;
aff255c8
PN
1735 robj *key = c->argv[1];
1736 robj *emptyreply, *zobj;
e2641e09 1737 int offset = 0, limit = -1;
1738 int withscores = 0;
25bb8a44
PN
1739 unsigned long rangelen = 0;
1740 void *replylen = NULL;
22b9bf15 1741 int minidx, maxidx;
e2641e09 1742
25bb8a44 1743 /* Parse the range arguments. */
22b9bf15
PN
1744 if (reverse) {
1745 /* Range is given as [max,min] */
1746 maxidx = 2; minidx = 3;
1747 } else {
1748 /* Range is given as [min,max] */
1749 minidx = 2; maxidx = 3;
1750 }
1751
1752 if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) {
7236fdb2
PN
1753 addReplyError(c,"min or max is not a double");
1754 return;
1755 }
25bb8a44
PN
1756
1757 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1758 * 4 arguments, so we'll never enter the following code path. */
1759 if (c->argc > 4) {
1760 int remaining = c->argc - 4;
1761 int pos = 4;
1762
1763 while (remaining) {
1764 if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) {
1765 pos++; remaining--;
1766 withscores = 1;
1767 } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
1768 offset = atoi(c->argv[pos+1]->ptr);
1769 limit = atoi(c->argv[pos+2]->ptr);
1770 pos += 3; remaining -= 3;
1771 } else {
1772 addReply(c,shared.syntaxerr);
1773 return;
1774 }
1775 }
e2641e09 1776 }
25bb8a44
PN
1777
1778 /* Ok, lookup the key and get the range */
1779 emptyreply = justcount ? shared.czero : shared.emptymultibulk;
aff255c8
PN
1780 if ((zobj = lookupKeyReadOrReply(c,key,emptyreply)) == NULL ||
1781 checkType(c,zobj,REDIS_ZSET)) return;
25bb8a44 1782
aff255c8
PN
1783 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1784 unsigned char *zl = zobj->ptr;
1785 unsigned char *eptr, *sptr;
1786 unsigned char *vstr;
1787 unsigned int vlen;
1788 long long vlong;
1789 double score;
e2641e09 1790
aff255c8
PN
1791 /* If reversed, get the last node in range as starting point. */
1792 if (reverse)
8588bfa3 1793 eptr = zzlLastInRange(zl,range);
aff255c8 1794 else
8588bfa3 1795 eptr = zzlFirstInRange(zl,range);
e2641e09 1796
aff255c8
PN
1797 /* No "first" element in the specified interval. */
1798 if (eptr == NULL) {
1799 addReply(c,emptyreply);
1800 return;
1801 }
e2641e09 1802
aff255c8
PN
1803 /* Get score pointer for the first element. */
1804 redisAssert(eptr != NULL);
1805 sptr = ziplistNext(zl,eptr);
e2641e09 1806
aff255c8
PN
1807 /* We don't know in advance how many matching elements there are in the
1808 * list, so we push this object that will represent the multi-bulk
1809 * length in the output buffer, and will "fix" it later */
1810 if (!justcount)
1811 replylen = addDeferredMultiBulkLength(c);
1812
1813 /* If there is an offset, just traverse the number of elements without
1814 * checking the score because that is done in the next loop. */
1815 while (eptr && offset--)
1816 if (reverse)
1817 zzlPrev(zl,&eptr,&sptr);
1818 else
1819 zzlNext(zl,&eptr,&sptr);
1820
1821 while (eptr && limit--) {
1822 score = zzlGetScore(sptr);
1823
1824 /* Abort when the node is no longer in range. */
1825 if (reverse) {
1826 if (!zslValueGteMin(score,&range)) break;
1827 } else {
1828 if (!zslValueLteMax(score,&range)) break;
1829 }
1830
1831 /* Do our magic */
1832 rangelen++;
1833 if (!justcount) {
1834 redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
1835 if (vstr == NULL)
1836 addReplyBulkLongLong(c,vlong);
1837 else
1838 addReplyBulkCBuffer(c,vstr,vlen);
1839
1840 if (withscores)
1841 addReplyDouble(c,score);
1842 }
1843
1844 /* Move to next node */
1845 if (reverse)
1846 zzlPrev(zl,&eptr,&sptr);
1847 else
1848 zzlNext(zl,&eptr,&sptr);
e2641e09 1849 }
aff255c8
PN
1850 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1851 zset *zs = zobj->ptr;
1852 zskiplist *zsl = zs->zsl;
1853 zskiplistNode *ln;
25bb8a44 1854
aff255c8
PN
1855 /* If reversed, get the last node in range as starting point. */
1856 if (reverse)
1857 ln = zslLastInRange(zsl,range);
1858 else
1859 ln = zslFirstInRange(zsl,range);
1860
1861 /* No "first" element in the specified interval. */
1862 if (ln == NULL) {
1863 addReply(c,emptyreply);
1864 return;
25bb8a44
PN
1865 }
1866
aff255c8
PN
1867 /* We don't know in advance how many matching elements there are in the
1868 * list, so we push this object that will represent the multi-bulk
1869 * length in the output buffer, and will "fix" it later */
1870 if (!justcount)
1871 replylen = addDeferredMultiBulkLength(c);
1872
1873 /* If there is an offset, just traverse the number of elements without
1874 * checking the score because that is done in the next loop. */
1875 while (ln && offset--)
1876 ln = reverse ? ln->backward : ln->level[0].forward;
1877
1878 while (ln && limit--) {
1879 /* Abort when the node is no longer in range. */
1880 if (reverse) {
1881 if (!zslValueGteMin(ln->score,&range)) break;
1882 } else {
1883 if (!zslValueLteMax(ln->score,&range)) break;
1884 }
1885
1886 /* Do our magic */
1887 rangelen++;
1888 if (!justcount) {
1889 addReplyBulk(c,ln->obj);
1890 if (withscores)
1891 addReplyDouble(c,ln->score);
1892 }
1893
1894 /* Move to next node */
1895 ln = reverse ? ln->backward : ln->level[0].forward;
1896 }
1897 } else {
1898 redisPanic("Unknown sorted set encoding");
25bb8a44
PN
1899 }
1900
1901 if (justcount) {
1902 addReplyLongLong(c,(long)rangelen);
1903 } else {
aff255c8
PN
1904 if (withscores) rangelen *= 2;
1905 setDeferredMultiBulkLength(c,replylen,rangelen);
e2641e09 1906 }
1907}
1908
1909void zrangebyscoreCommand(redisClient *c) {
25bb8a44
PN
1910 genericZrangebyscoreCommand(c,0,0);
1911}
1912
1913void zrevrangebyscoreCommand(redisClient *c) {
1914 genericZrangebyscoreCommand(c,1,0);
e2641e09 1915}
1916
1917void zcountCommand(redisClient *c) {
25bb8a44 1918 genericZrangebyscoreCommand(c,0,1);
e2641e09 1919}
1920
1921void zcardCommand(redisClient *c) {
d1c920c5
PN
1922 robj *key = c->argv[1];
1923 robj *zobj;
e2641e09 1924
d1c920c5
PN
1925 if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL ||
1926 checkType(c,zobj,REDIS_ZSET)) return;
e2641e09 1927
df26a0ae 1928 addReplyLongLong(c,zsetLength(zobj));
e2641e09 1929}
1930
1931void zscoreCommand(redisClient *c) {
d1c920c5
PN
1932 robj *key = c->argv[1];
1933 robj *zobj;
1934 double score;
e2641e09 1935
d1c920c5
PN
1936 if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
1937 checkType(c,zobj,REDIS_ZSET)) return;
e2641e09 1938
d1c920c5 1939 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
8588bfa3 1940 if (zzlFind(zobj->ptr,c->argv[2],&score) != NULL)
d1c920c5
PN
1941 addReplyDouble(c,score);
1942 else
1943 addReply(c,shared.nullbulk);
1944 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1945 zset *zs = zobj->ptr;
1946 dictEntry *de;
e2641e09 1947
d1c920c5
PN
1948 c->argv[2] = tryObjectEncoding(c->argv[2]);
1949 de = dictFind(zs->dict,c->argv[2]);
1950 if (de != NULL) {
1951 score = *(double*)dictGetEntryVal(de);
1952 addReplyDouble(c,score);
1953 } else {
1954 addReply(c,shared.nullbulk);
1955 }
1956 } else {
1957 redisPanic("Unknown sorted set encoding");
e2641e09 1958 }
1959}
1960
1961void zrankGenericCommand(redisClient *c, int reverse) {
d1c920c5
PN
1962 robj *key = c->argv[1];
1963 robj *ele = c->argv[2];
1964 robj *zobj;
1965 unsigned long llen;
e2641e09 1966 unsigned long rank;
e2641e09 1967
d1c920c5
PN
1968 if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
1969 checkType(c,zobj,REDIS_ZSET)) return;
df26a0ae 1970 llen = zsetLength(zobj);
e2641e09 1971
d1c920c5
PN
1972 redisAssert(ele->encoding == REDIS_ENCODING_RAW);
1973 if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1974 unsigned char *zl = zobj->ptr;
1975 unsigned char *eptr, *sptr;
e2641e09 1976
d1c920c5
PN
1977 eptr = ziplistIndex(zl,0);
1978 redisAssert(eptr != NULL);
1979 sptr = ziplistNext(zl,eptr);
1980 redisAssert(sptr != NULL);
1981
1982 rank = 1;
1983 while(eptr != NULL) {
1984 if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr)))
1985 break;
1986 rank++;
1987 zzlNext(zl,&eptr,&sptr);
1988 }
1989
1990 if (eptr != NULL) {
1991 if (reverse)
1992 addReplyLongLong(c,llen-rank);
1993 else
1994 addReplyLongLong(c,rank-1);
e2641e09 1995 } else {
d1c920c5
PN
1996 addReply(c,shared.nullbulk);
1997 }
1998 } else if (zobj->encoding == REDIS_ENCODING_RAW) {
1999 zset *zs = zobj->ptr;
2000 zskiplist *zsl = zs->zsl;
2001 dictEntry *de;
2002 double score;
2003
2004 ele = c->argv[2] = tryObjectEncoding(c->argv[2]);
2005 de = dictFind(zs->dict,ele);
2006 if (de != NULL) {
2007 score = *(double*)dictGetEntryVal(de);
2008 rank = zslGetRank(zsl,score,ele);
2009 redisAssert(rank); /* Existing elements always have a rank. */
2010 if (reverse)
2011 addReplyLongLong(c,llen-rank);
2012 else
2013 addReplyLongLong(c,rank-1);
2014 } else {
2015 addReply(c,shared.nullbulk);
e2641e09 2016 }
2017 } else {
d1c920c5 2018 redisPanic("Unknown sorted set encoding");
e2641e09 2019 }
2020}
2021
2022void zrankCommand(redisClient *c) {
2023 zrankGenericCommand(c, 0);
2024}
2025
2026void zrevrankCommand(redisClient *c) {
2027 zrankGenericCommand(c, 1);
2028}