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