5 /*-----------------------------------------------------------------------------
7 *----------------------------------------------------------------------------*/
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
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"). */
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. */
26 zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
27 zskiplistNode
*zn
= zmalloc(sizeof(*zn
));
29 zn
->forward
= zmalloc(sizeof(zskiplistNode
*) * level
);
31 zn
->span
= zmalloc(sizeof(unsigned int) * (level
- 1));
39 zskiplist
*zslCreate(void) {
43 zsl
= zmalloc(sizeof(*zsl
));
46 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
47 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
48 zsl
->header
->forward
[j
] = NULL
;
50 /* span has space for ZSKIPLIST_MAXLEVEL-1 elements */
51 if (j
< ZSKIPLIST_MAXLEVEL
-1)
52 zsl
->header
->span
[j
] = 0;
54 zsl
->header
->backward
= NULL
;
59 void zslFreeNode(zskiplistNode
*node
) {
60 decrRefCount(node
->obj
);
66 void zslFree(zskiplist
*zsl
) {
67 zskiplistNode
*node
= zsl
->header
->forward
[0], *next
;
69 zfree(zsl
->header
->forward
);
70 zfree(zsl
->header
->span
);
73 next
= node
->forward
[0];
80 int zslRandomLevel(void) {
82 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
84 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
87 void zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
88 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
89 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
93 for (i
= zsl
->level
-1; i
>= 0; i
--) {
94 /* store rank that is crossed to reach the insert position */
95 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
97 while (x
->forward
[i
] &&
98 (x
->forward
[i
]->score
< score
||
99 (x
->forward
[i
]->score
== score
&&
100 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0))) {
101 rank
[i
] += i
> 0 ? x
->span
[i
-1] : 1;
106 /* we assume the key is not already inside, since we allow duplicated
107 * scores, and the re-insertion of score and redis object should never
108 * happpen since the caller of zslInsert() should test in the hash table
109 * if the element is already inside or not. */
110 level
= zslRandomLevel();
111 if (level
> zsl
->level
) {
112 for (i
= zsl
->level
; i
< level
; i
++) {
114 update
[i
] = zsl
->header
;
115 update
[i
]->span
[i
-1] = zsl
->length
;
119 x
= zslCreateNode(level
,score
,obj
);
120 for (i
= 0; i
< level
; i
++) {
121 x
->forward
[i
] = update
[i
]->forward
[i
];
122 update
[i
]->forward
[i
] = x
;
124 /* update span covered by update[i] as x is inserted here */
126 x
->span
[i
-1] = update
[i
]->span
[i
-1] - (rank
[0] - rank
[i
]);
127 update
[i
]->span
[i
-1] = (rank
[0] - rank
[i
]) + 1;
131 /* increment span for untouched levels */
132 for (i
= level
; i
< zsl
->level
; i
++) {
133 update
[i
]->span
[i
-1]++;
136 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
138 x
->forward
[0]->backward
= x
;
144 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
145 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
147 for (i
= 0; i
< zsl
->level
; i
++) {
148 if (update
[i
]->forward
[i
] == x
) {
150 update
[i
]->span
[i
-1] += x
->span
[i
-1] - 1;
152 update
[i
]->forward
[i
] = x
->forward
[i
];
154 /* invariant: i > 0, because update[0]->forward[0]
155 * is always equal to x */
156 update
[i
]->span
[i
-1] -= 1;
160 x
->forward
[0]->backward
= x
->backward
;
162 zsl
->tail
= x
->backward
;
164 while(zsl
->level
> 1 && zsl
->header
->forward
[zsl
->level
-1] == NULL
)
169 /* Delete an element with matching score/object from the skiplist. */
170 int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
171 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
175 for (i
= zsl
->level
-1; i
>= 0; i
--) {
176 while (x
->forward
[i
] &&
177 (x
->forward
[i
]->score
< score
||
178 (x
->forward
[i
]->score
== score
&&
179 compareStringObjects(x
->forward
[i
]->obj
,obj
) < 0)))
183 /* We may have multiple elements with the same score, what we need
184 * is to find the element with both the right score and object. */
186 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
187 zslDeleteNode(zsl
, x
, update
);
191 return 0; /* not found */
193 return 0; /* not found */
196 /* Delete all the elements with score between min and max from the skiplist.
197 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
198 * Note that this function takes the reference to the hash table view of the
199 * sorted set, in order to remove the elements from the hash table too. */
200 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
201 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
202 unsigned long removed
= 0;
206 for (i
= zsl
->level
-1; i
>= 0; i
--) {
207 while (x
->forward
[i
] && x
->forward
[i
]->score
< min
)
211 /* We may have multiple elements with the same score, what we need
212 * is to find the element with both the right score and object. */
214 while (x
&& x
->score
<= max
) {
215 zskiplistNode
*next
= x
->forward
[0];
216 zslDeleteNode(zsl
, x
, update
);
217 dictDelete(dict
,x
->obj
);
222 return removed
; /* not found */
225 /* Delete all the elements with rank between start and end from the skiplist.
226 * Start and end are inclusive. Note that start and end need to be 1-based */
227 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
228 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
229 unsigned long traversed
= 0, removed
= 0;
233 for (i
= zsl
->level
-1; i
>= 0; i
--) {
234 while (x
->forward
[i
] && (traversed
+ (i
> 0 ? x
->span
[i
-1] : 1)) < start
) {
235 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
243 while (x
&& traversed
<= end
) {
244 zskiplistNode
*next
= x
->forward
[0];
245 zslDeleteNode(zsl
, x
, update
);
246 dictDelete(dict
,x
->obj
);
255 /* Find the first node having a score equal or greater than the specified one.
256 * Returns NULL if there is no match. */
257 zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
262 for (i
= zsl
->level
-1; i
>= 0; i
--) {
263 while (x
->forward
[i
] && x
->forward
[i
]->score
< score
)
266 /* We may have multiple elements with the same score, what we need
267 * is to find the element with both the right score and object. */
268 return x
->forward
[0];
271 /* Find the rank for an element by both score and key.
272 * Returns 0 when the element cannot be found, rank otherwise.
273 * Note that the rank is 1-based due to the span of zsl->header to the
275 unsigned long zslistTypeGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
277 unsigned long rank
= 0;
281 for (i
= zsl
->level
-1; i
>= 0; i
--) {
282 while (x
->forward
[i
] &&
283 (x
->forward
[i
]->score
< score
||
284 (x
->forward
[i
]->score
== score
&&
285 compareStringObjects(x
->forward
[i
]->obj
,o
) <= 0))) {
286 rank
+= i
> 0 ? x
->span
[i
-1] : 1;
290 /* x might be equal to zsl->header, so test if obj is non-NULL */
291 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
298 /* Finds an element by its rank. The rank argument needs to be 1-based. */
299 zskiplistNode
* zslistTypeGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
301 unsigned long traversed
= 0;
305 for (i
= zsl
->level
-1; i
>= 0; i
--) {
306 while (x
->forward
[i
] && (traversed
+ (i
>0 ? x
->span
[i
-1] : 1)) <= rank
)
308 traversed
+= i
> 0 ? x
->span
[i
-1] : 1;
311 if (traversed
== rank
) {
318 /*-----------------------------------------------------------------------------
319 * Sorted set commands
320 *----------------------------------------------------------------------------*/
322 /* This generic command implements both ZADD and ZINCRBY.
323 * scoreval is the score if the operation is a ZADD (doincrement == 0) or
324 * the increment if the operation is a ZINCRBY (doincrement == 1). */
325 void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double scoreval
, int doincrement
) {
330 if (isnan(scoreval
)) {
331 addReplySds(c
,sdsnew("-ERR provide score is Not A Number (nan)\r\n"));
335 zsetobj
= lookupKeyWrite(c
->db
,key
);
336 if (zsetobj
== NULL
) {
337 zsetobj
= createZsetObject();
338 dbAdd(c
->db
,key
,zsetobj
);
340 if (zsetobj
->type
!= REDIS_ZSET
) {
341 addReply(c
,shared
.wrongtypeerr
);
347 /* Ok now since we implement both ZADD and ZINCRBY here the code
348 * needs to handle the two different conditions. It's all about setting
349 * '*score', that is, the new score to set, to the right value. */
350 score
= zmalloc(sizeof(double));
354 /* Read the old score. If the element was not present starts from 0 */
355 de
= dictFind(zs
->dict
,ele
);
357 double *oldscore
= dictGetEntryVal(de
);
358 *score
= *oldscore
+ scoreval
;
364 sdsnew("-ERR resulting score is Not A Number (nan)\r\n"));
366 /* Note that we don't need to check if the zset may be empty and
367 * should be removed here, as we can only obtain Nan as score if
368 * there was already an element in the sorted set. */
375 /* What follows is a simple remove and re-insert operation that is common
376 * to both ZADD and ZINCRBY... */
377 if (dictAdd(zs
->dict
,ele
,score
) == DICT_OK
) {
378 /* case 1: New element */
379 incrRefCount(ele
); /* added to hash */
380 zslInsert(zs
->zsl
,*score
,ele
);
381 incrRefCount(ele
); /* added to skiplist */
382 touchWatchedKey(c
->db
,c
->argv
[1]);
385 addReplyDouble(c
,*score
);
387 addReply(c
,shared
.cone
);
392 /* case 2: Score update operation */
393 de
= dictFind(zs
->dict
,ele
);
394 redisAssert(de
!= NULL
);
395 oldscore
= dictGetEntryVal(de
);
396 if (*score
!= *oldscore
) {
399 /* Remove and insert the element in the skip list with new score */
400 deleted
= zslDelete(zs
->zsl
,*oldscore
,ele
);
401 redisAssert(deleted
!= 0);
402 zslInsert(zs
->zsl
,*score
,ele
);
404 /* Update the score in the hash table */
405 dictReplace(zs
->dict
,ele
,score
);
406 touchWatchedKey(c
->db
,c
->argv
[1]);
412 addReplyDouble(c
,*score
);
414 addReply(c
,shared
.czero
);
418 void zaddCommand(redisClient
*c
) {
421 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
422 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
425 void zincrbyCommand(redisClient
*c
) {
428 if (getDoubleFromObjectOrReply(c
, c
->argv
[2], &scoreval
, NULL
) != REDIS_OK
) return;
429 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
432 void zremCommand(redisClient
*c
) {
439 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
440 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
443 de
= dictFind(zs
->dict
,c
->argv
[2]);
445 addReply(c
,shared
.czero
);
448 /* Delete from the skiplist */
449 oldscore
= dictGetEntryVal(de
);
450 deleted
= zslDelete(zs
->zsl
,*oldscore
,c
->argv
[2]);
451 redisAssert(deleted
!= 0);
453 /* Delete from the hash table */
454 dictDelete(zs
->dict
,c
->argv
[2]);
455 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
456 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
457 touchWatchedKey(c
->db
,c
->argv
[1]);
459 addReply(c
,shared
.cone
);
462 void zremrangebyscoreCommand(redisClient
*c
) {
469 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
470 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
472 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
473 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
476 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
477 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
478 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
479 if (deleted
) touchWatchedKey(c
->db
,c
->argv
[1]);
480 server
.dirty
+= deleted
;
481 addReplyLongLong(c
,deleted
);
484 void zremrangebyrankCommand(redisClient
*c
) {
492 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
493 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
495 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
496 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
498 llen
= zs
->zsl
->length
;
500 /* convert negative indexes */
501 if (start
< 0) start
= llen
+start
;
502 if (end
< 0) end
= llen
+end
;
503 if (start
< 0) start
= 0;
505 /* Invariant: start >= 0, so this test will be true when end < 0.
506 * The range is empty when start > end or start >= length. */
507 if (start
> end
|| start
>= llen
) {
508 addReply(c
,shared
.czero
);
511 if (end
>= llen
) end
= llen
-1;
513 /* increment start and end because zsl*Rank functions
514 * use 1-based rank */
515 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
516 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
517 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
518 if (deleted
) touchWatchedKey(c
->db
,c
->argv
[1]);
519 server
.dirty
+= deleted
;
520 addReplyLongLong(c
, deleted
);
528 int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
529 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
530 unsigned long size1
, size2
;
531 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
532 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
533 return size1
- size2
;
536 #define REDIS_AGGR_SUM 1
537 #define REDIS_AGGR_MIN 2
538 #define REDIS_AGGR_MAX 3
539 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
541 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
542 if (aggregate
== REDIS_AGGR_SUM
) {
543 *target
= *target
+ val
;
544 } else if (aggregate
== REDIS_AGGR_MIN
) {
545 *target
= val
< *target
? val
: *target
;
546 } else if (aggregate
== REDIS_AGGR_MAX
) {
547 *target
= val
> *target
? val
: *target
;
550 redisPanic("Unknown ZUNION/INTER aggregate type");
554 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
556 int aggregate
= REDIS_AGGR_SUM
;
563 /* expect setnum input keys to be given */
564 setnum
= atoi(c
->argv
[2]->ptr
);
566 addReplySds(c
,sdsnew("-ERR at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE\r\n"));
570 /* test if the expected number of keys would overflow */
571 if (3+setnum
> c
->argc
) {
572 addReply(c
,shared
.syntaxerr
);
576 /* read keys to be used for input */
577 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
578 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
579 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
583 if (obj
->type
== REDIS_ZSET
) {
584 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
585 } else if (obj
->type
== REDIS_SET
) {
586 src
[i
].dict
= (obj
->ptr
);
589 addReply(c
,shared
.wrongtypeerr
);
594 /* default all weights to 1 */
598 /* parse optional extra arguments */
600 int remaining
= c
->argc
- j
;
603 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
605 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
606 if (getDoubleFromObjectOrReply(c
, c
->argv
[j
], &src
[i
].weight
, NULL
) != REDIS_OK
)
609 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
611 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
612 aggregate
= REDIS_AGGR_SUM
;
613 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
614 aggregate
= REDIS_AGGR_MIN
;
615 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
616 aggregate
= REDIS_AGGR_MAX
;
619 addReply(c
,shared
.syntaxerr
);
625 addReply(c
,shared
.syntaxerr
);
631 /* sort sets from the smallest to largest, this will improve our
632 * algorithm's performance */
633 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
635 dstobj
= createZsetObject();
636 dstzset
= dstobj
->ptr
;
638 if (op
== REDIS_OP_INTER
) {
639 /* skip going over all entries if the smallest zset is NULL or empty */
640 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
641 /* precondition: as src[0].dict is non-empty and the zsets are ordered
642 * from small to large, all src[i > 0].dict are non-empty too */
643 di
= dictGetIterator(src
[0].dict
);
644 while((de
= dictNext(di
)) != NULL
) {
645 double *score
= zmalloc(sizeof(double)), value
;
646 *score
= src
[0].weight
* zunionInterDictValue(de
);
648 for (j
= 1; j
< setnum
; j
++) {
649 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
651 value
= src
[j
].weight
* zunionInterDictValue(other
);
652 zunionInterAggregate(score
, value
, aggregate
);
658 /* skip entry when not present in every source dict */
662 robj
*o
= dictGetEntryKey(de
);
663 dictAdd(dstzset
->dict
,o
,score
);
664 incrRefCount(o
); /* added to dictionary */
665 zslInsert(dstzset
->zsl
,*score
,o
);
666 incrRefCount(o
); /* added to skiplist */
669 dictReleaseIterator(di
);
671 } else if (op
== REDIS_OP_UNION
) {
672 for (i
= 0; i
< setnum
; i
++) {
673 if (!src
[i
].dict
) continue;
675 di
= dictGetIterator(src
[i
].dict
);
676 while((de
= dictNext(di
)) != NULL
) {
677 /* skip key when already processed */
678 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
) continue;
680 double *score
= zmalloc(sizeof(double)), value
;
681 *score
= src
[i
].weight
* zunionInterDictValue(de
);
683 /* because the zsets are sorted by size, its only possible
684 * for sets at larger indices to hold this entry */
685 for (j
= (i
+1); j
< setnum
; j
++) {
686 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
688 value
= src
[j
].weight
* zunionInterDictValue(other
);
689 zunionInterAggregate(score
, value
, aggregate
);
693 robj
*o
= dictGetEntryKey(de
);
694 dictAdd(dstzset
->dict
,o
,score
);
695 incrRefCount(o
); /* added to dictionary */
696 zslInsert(dstzset
->zsl
,*score
,o
);
697 incrRefCount(o
); /* added to skiplist */
699 dictReleaseIterator(di
);
702 /* unknown operator */
703 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
706 dbDelete(c
->db
,dstkey
);
707 if (dstzset
->zsl
->length
) {
708 dbAdd(c
->db
,dstkey
,dstobj
);
709 addReplyLongLong(c
, dstzset
->zsl
->length
);
710 touchWatchedKey(c
->db
,dstkey
);
713 decrRefCount(dstobj
);
714 addReply(c
, shared
.czero
);
719 void zunionstoreCommand(redisClient
*c
) {
720 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
723 void zinterstoreCommand(redisClient
*c
) {
724 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
727 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
739 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
740 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
742 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
744 } else if (c
->argc
>= 5) {
745 addReply(c
,shared
.syntaxerr
);
749 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
750 || checkType(c
,o
,REDIS_ZSET
)) return;
755 /* convert negative indexes */
756 if (start
< 0) start
= llen
+start
;
757 if (end
< 0) end
= llen
+end
;
758 if (start
< 0) start
= 0;
760 /* Invariant: start >= 0, so this test will be true when end < 0.
761 * The range is empty when start > end or start >= length. */
762 if (start
> end
|| start
>= llen
) {
763 addReply(c
,shared
.emptymultibulk
);
766 if (end
>= llen
) end
= llen
-1;
767 rangelen
= (end
-start
)+1;
769 /* check if starting point is trivial, before searching
770 * the element in log(N) time */
772 ln
= start
== 0 ? zsl
->tail
: zslistTypeGetElementByRank(zsl
, llen
-start
);
775 zsl
->header
->forward
[0] : zslistTypeGetElementByRank(zsl
, start
+1);
778 /* Return the result in form of a multi-bulk reply */
779 addReplySds(c
,sdscatprintf(sdsempty(),"*%d\r\n",
780 withscores
? (rangelen
*2) : rangelen
));
781 for (j
= 0; j
< rangelen
; j
++) {
785 addReplyDouble(c
,ln
->score
);
786 ln
= reverse
? ln
->backward
: ln
->forward
[0];
790 void zrangeCommand(redisClient
*c
) {
791 zrangeGenericCommand(c
,0);
794 void zrevrangeCommand(redisClient
*c
) {
795 zrangeGenericCommand(c
,1);
798 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
799 * If justcount is non-zero, just the count is returned. */
800 void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
803 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
804 int offset
= 0, limit
= -1;
808 /* Parse the min-max interval. If one of the values is prefixed
809 * by the "(" character, it's considered "open". For instance
810 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
811 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
812 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
813 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
816 min
= strtod(c
->argv
[2]->ptr
,NULL
);
818 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
819 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
822 max
= strtod(c
->argv
[3]->ptr
,NULL
);
825 /* Parse "WITHSCORES": note that if the command was called with
826 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
827 * enter the following paths to parse WITHSCORES and LIMIT. */
828 if (c
->argc
== 5 || c
->argc
== 8) {
829 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
834 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
838 sdsnew("-ERR wrong number of arguments for ZRANGEBYSCORE\r\n"));
843 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
844 addReply(c
,shared
.syntaxerr
);
846 } else if (c
->argc
== (7 + withscores
)) {
847 offset
= atoi(c
->argv
[5]->ptr
);
848 limit
= atoi(c
->argv
[6]->ptr
);
849 if (offset
< 0) offset
= 0;
852 /* Ok, lookup the key and get the range */
853 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
855 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
857 if (o
->type
!= REDIS_ZSET
) {
858 addReply(c
,shared
.wrongtypeerr
);
860 zset
*zsetobj
= o
->ptr
;
861 zskiplist
*zsl
= zsetobj
->zsl
;
863 robj
*ele
, *lenobj
= NULL
;
864 unsigned long rangelen
= 0;
866 /* Get the first node with the score >= min, or with
867 * score > min if 'minex' is true. */
868 ln
= zslFirstWithScore(zsl
,min
);
869 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->forward
[0];
872 /* No element matching the speciifed interval */
873 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
877 /* We don't know in advance how many matching elements there
878 * are in the list, so we push this object that will represent
879 * the multi-bulk length in the output buffer, and will "fix"
882 lenobj
= createObject(REDIS_STRING
,NULL
);
884 decrRefCount(lenobj
);
887 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
893 if (limit
== 0) break;
898 addReplyDouble(c
,ln
->score
);
902 if (limit
> 0) limit
--;
905 addReplyLongLong(c
,(long)rangelen
);
907 lenobj
->ptr
= sdscatprintf(sdsempty(),"*%lu\r\n",
908 withscores
? (rangelen
*2) : rangelen
);
914 void zrangebyscoreCommand(redisClient
*c
) {
915 genericZrangebyscoreCommand(c
,0);
918 void zcountCommand(redisClient
*c
) {
919 genericZrangebyscoreCommand(c
,1);
922 void zcardCommand(redisClient
*c
) {
926 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
927 checkType(c
,o
,REDIS_ZSET
)) return;
930 addReplyUlong(c
,zs
->zsl
->length
);
933 void zscoreCommand(redisClient
*c
) {
938 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
939 checkType(c
,o
,REDIS_ZSET
)) return;
942 de
= dictFind(zs
->dict
,c
->argv
[2]);
944 addReply(c
,shared
.nullbulk
);
946 double *score
= dictGetEntryVal(de
);
948 addReplyDouble(c
,*score
);
952 void zrankGenericCommand(redisClient
*c
, int reverse
) {
960 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
961 checkType(c
,o
,REDIS_ZSET
)) return;
965 de
= dictFind(zs
->dict
,c
->argv
[2]);
967 addReply(c
,shared
.nullbulk
);
971 score
= dictGetEntryVal(de
);
972 rank
= zslistTypeGetRank(zsl
, *score
, c
->argv
[2]);
975 addReplyLongLong(c
, zsl
->length
- rank
);
977 addReplyLongLong(c
, rank
-1);
980 addReply(c
,shared
.nullbulk
);
984 void zrankCommand(redisClient
*c
) {
985 zrankGenericCommand(c
, 0);
988 void zrevrankCommand(redisClient
*c
) {
989 zrankGenericCommand(c
, 1);