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
)+level
*sizeof(struct zskiplistLevel
));
33 zskiplist
*zslCreate(void) {
37 zsl
= zmalloc(sizeof(*zsl
));
40 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
41 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
42 zsl
->header
->level
[j
].forward
= NULL
;
43 zsl
->header
->level
[j
].span
= 0;
45 zsl
->header
->backward
= NULL
;
50 void zslFreeNode(zskiplistNode
*node
) {
51 decrRefCount(node
->obj
);
55 void zslFree(zskiplist
*zsl
) {
56 zskiplistNode
*node
= zsl
->header
->level
[0].forward
, *next
;
60 next
= node
->level
[0].forward
;
67 int zslRandomLevel(void) {
69 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
71 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
74 zskiplistNode
*zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
75 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
76 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
80 for (i
= zsl
->level
-1; i
>= 0; i
--) {
81 /* store rank that is crossed to reach the insert position */
82 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
83 while (x
->level
[i
].forward
&&
84 (x
->level
[i
].forward
->score
< score
||
85 (x
->level
[i
].forward
->score
== score
&&
86 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0))) {
87 rank
[i
] += x
->level
[i
].span
;
88 x
= x
->level
[i
].forward
;
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
++) {
100 update
[i
] = zsl
->header
;
101 update
[i
]->level
[i
].span
= zsl
->length
;
105 x
= zslCreateNode(level
,score
,obj
);
106 for (i
= 0; i
< level
; i
++) {
107 x
->level
[i
].forward
= update
[i
]->level
[i
].forward
;
108 update
[i
]->level
[i
].forward
= x
;
110 /* update span covered by update[i] as x is inserted here */
111 x
->level
[i
].span
= update
[i
]->level
[i
].span
- (rank
[0] - rank
[i
]);
112 update
[i
]->level
[i
].span
= (rank
[0] - rank
[i
]) + 1;
115 /* increment span for untouched levels */
116 for (i
= level
; i
< zsl
->level
; i
++) {
117 update
[i
]->level
[i
].span
++;
120 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
121 if (x
->level
[0].forward
)
122 x
->level
[0].forward
->backward
= x
;
129 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
130 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
132 for (i
= 0; i
< zsl
->level
; i
++) {
133 if (update
[i
]->level
[i
].forward
== x
) {
134 update
[i
]->level
[i
].span
+= x
->level
[i
].span
- 1;
135 update
[i
]->level
[i
].forward
= x
->level
[i
].forward
;
137 update
[i
]->level
[i
].span
-= 1;
140 if (x
->level
[0].forward
) {
141 x
->level
[0].forward
->backward
= x
->backward
;
143 zsl
->tail
= x
->backward
;
145 while(zsl
->level
> 1 && zsl
->header
->level
[zsl
->level
-1].forward
== NULL
)
150 /* Delete an element with matching score/object from the skiplist. */
151 int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
152 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
156 for (i
= zsl
->level
-1; i
>= 0; i
--) {
157 while (x
->level
[i
].forward
&&
158 (x
->level
[i
].forward
->score
< score
||
159 (x
->level
[i
].forward
->score
== score
&&
160 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0)))
161 x
= x
->level
[i
].forward
;
164 /* We may have multiple elements with the same score, what we need
165 * is to find the element with both the right score and object. */
166 x
= x
->level
[0].forward
;
167 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
168 zslDeleteNode(zsl
, x
, update
);
172 return 0; /* not found */
174 return 0; /* not found */
177 /* Delete all the elements with score between min and max from the skiplist.
178 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
179 * Note that this function takes the reference to the hash table view of the
180 * sorted set, in order to remove the elements from the hash table too. */
181 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, double min
, double max
, dict
*dict
) {
182 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
183 unsigned long removed
= 0;
187 for (i
= zsl
->level
-1; i
>= 0; i
--) {
188 while (x
->level
[i
].forward
&& x
->level
[i
].forward
->score
< min
)
189 x
= x
->level
[i
].forward
;
192 /* We may have multiple elements with the same score, what we need
193 * is to find the element with both the right score and object. */
194 x
= x
->level
[0].forward
;
195 while (x
&& x
->score
<= max
) {
196 zskiplistNode
*next
= x
->level
[0].forward
;
197 zslDeleteNode(zsl
,x
,update
);
198 dictDelete(dict
,x
->obj
);
203 return removed
; /* not found */
206 /* Delete all the elements with rank between start and end from the skiplist.
207 * Start and end are inclusive. Note that start and end need to be 1-based */
208 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
209 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
210 unsigned long traversed
= 0, removed
= 0;
214 for (i
= zsl
->level
-1; i
>= 0; i
--) {
215 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
216 traversed
+= x
->level
[i
].span
;
217 x
= x
->level
[i
].forward
;
223 x
= x
->level
[0].forward
;
224 while (x
&& traversed
<= end
) {
225 zskiplistNode
*next
= x
->level
[0].forward
;
226 zslDeleteNode(zsl
,x
,update
);
227 dictDelete(dict
,x
->obj
);
236 /* Find the first node having a score equal or greater than the specified one.
237 * Returns NULL if there is no match. */
238 zskiplistNode
*zslFirstWithScore(zskiplist
*zsl
, double score
) {
243 for (i
= zsl
->level
-1; i
>= 0; i
--) {
244 while (x
->level
[i
].forward
&& x
->level
[i
].forward
->score
< score
)
245 x
= x
->level
[i
].forward
;
247 /* We may have multiple elements with the same score, what we need
248 * is to find the element with both the right score and object. */
249 return x
->level
[0].forward
;
252 /* Find the rank for an element by both score and key.
253 * Returns 0 when the element cannot be found, rank otherwise.
254 * Note that the rank is 1-based due to the span of zsl->header to the
256 unsigned long zslistTypeGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
258 unsigned long rank
= 0;
262 for (i
= zsl
->level
-1; i
>= 0; i
--) {
263 while (x
->level
[i
].forward
&&
264 (x
->level
[i
].forward
->score
< score
||
265 (x
->level
[i
].forward
->score
== score
&&
266 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
267 rank
+= x
->level
[i
].span
;
268 x
= x
->level
[i
].forward
;
271 /* x might be equal to zsl->header, so test if obj is non-NULL */
272 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
279 /* Finds an element by its rank. The rank argument needs to be 1-based. */
280 zskiplistNode
* zslistTypeGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
282 unsigned long traversed
= 0;
286 for (i
= zsl
->level
-1; i
>= 0; i
--) {
287 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
289 traversed
+= x
->level
[i
].span
;
290 x
= x
->level
[i
].forward
;
292 if (traversed
== rank
) {
299 /*-----------------------------------------------------------------------------
300 * Sorted set commands
301 *----------------------------------------------------------------------------*/
303 /* This generic command implements both ZADD and ZINCRBY. */
304 void zaddGenericCommand(redisClient
*c
, robj
*key
, robj
*ele
, double score
, int incr
) {
307 zskiplistNode
*znode
;
309 zsetobj
= lookupKeyWrite(c
->db
,key
);
310 if (zsetobj
== NULL
) {
311 zsetobj
= createZsetObject();
312 dbAdd(c
->db
,key
,zsetobj
);
314 if (zsetobj
->type
!= REDIS_ZSET
) {
315 addReply(c
,shared
.wrongtypeerr
);
321 /* Since both ZADD and ZINCRBY are implemented here, we need to increment
322 * the score first by the current score if ZINCRBY is called. */
324 /* Read the old score. If the element was not present starts from 0 */
325 dictEntry
*de
= dictFind(zs
->dict
,ele
);
327 score
+= *(double*)dictGetEntryVal(de
);
330 addReplyError(c
,"resulting score is not a number (NaN)");
331 /* Note that we don't need to check if the zset may be empty and
332 * should be removed here, as we can only obtain Nan as score if
333 * there was already an element in the sorted set. */
338 /* We need to remove and re-insert the element when it was already present
339 * in the dictionary, to update the skiplist. Note that we delay adding a
340 * pointer to the score because we want to reference the score in the
342 if (dictAdd(zs
->dict
,ele
,NULL
) == DICT_OK
) {
346 incrRefCount(ele
); /* added to hash */
347 znode
= zslInsert(zs
->zsl
,score
,ele
);
348 incrRefCount(ele
); /* added to skiplist */
350 /* Update the score in the dict entry */
351 de
= dictFind(zs
->dict
,ele
);
352 redisAssert(de
!= NULL
);
353 dictGetEntryVal(de
) = &znode
->score
;
354 touchWatchedKey(c
->db
,c
->argv
[1]);
357 addReplyDouble(c
,score
);
359 addReply(c
,shared
.cone
);
367 de
= dictFind(zs
->dict
,ele
);
368 redisAssert(de
!= NULL
);
369 curobj
= dictGetEntryKey(de
);
370 curscore
= dictGetEntryVal(de
);
372 /* When the score is updated, reuse the existing string object to
373 * prevent extra alloc/dealloc of strings on ZINCRBY. */
374 if (score
!= *curscore
) {
375 deleted
= zslDelete(zs
->zsl
,*curscore
,curobj
);
376 redisAssert(deleted
!= 0);
377 znode
= zslInsert(zs
->zsl
,score
,curobj
);
378 incrRefCount(curobj
);
380 /* Update the score in the current dict entry */
381 dictGetEntryVal(de
) = &znode
->score
;
382 touchWatchedKey(c
->db
,c
->argv
[1]);
386 addReplyDouble(c
,score
);
388 addReply(c
,shared
.czero
);
392 void zaddCommand(redisClient
*c
) {
394 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&scoreval
,NULL
) != REDIS_OK
) return;
395 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,0);
398 void zincrbyCommand(redisClient
*c
) {
400 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&scoreval
,NULL
) != REDIS_OK
) return;
401 zaddGenericCommand(c
,c
->argv
[1],c
->argv
[3],scoreval
,1);
404 void zremCommand(redisClient
*c
) {
411 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
412 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
415 de
= dictFind(zs
->dict
,c
->argv
[2]);
417 addReply(c
,shared
.czero
);
420 /* Delete from the skiplist */
421 curscore
= *(double*)dictGetEntryVal(de
);
422 deleted
= zslDelete(zs
->zsl
,curscore
,c
->argv
[2]);
423 redisAssert(deleted
!= 0);
425 /* Delete from the hash table */
426 dictDelete(zs
->dict
,c
->argv
[2]);
427 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
428 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
429 touchWatchedKey(c
->db
,c
->argv
[1]);
431 addReply(c
,shared
.cone
);
434 void zremrangebyscoreCommand(redisClient
*c
) {
441 if ((getDoubleFromObjectOrReply(c
, c
->argv
[2], &min
, NULL
) != REDIS_OK
) ||
442 (getDoubleFromObjectOrReply(c
, c
->argv
[3], &max
, NULL
) != REDIS_OK
)) return;
444 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
445 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
448 deleted
= zslDeleteRangeByScore(zs
->zsl
,min
,max
,zs
->dict
);
449 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
450 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
451 if (deleted
) touchWatchedKey(c
->db
,c
->argv
[1]);
452 server
.dirty
+= deleted
;
453 addReplyLongLong(c
,deleted
);
456 void zremrangebyrankCommand(redisClient
*c
) {
464 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
465 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
467 if ((zsetobj
= lookupKeyWriteOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
468 checkType(c
,zsetobj
,REDIS_ZSET
)) return;
470 llen
= zs
->zsl
->length
;
472 /* convert negative indexes */
473 if (start
< 0) start
= llen
+start
;
474 if (end
< 0) end
= llen
+end
;
475 if (start
< 0) start
= 0;
477 /* Invariant: start >= 0, so this test will be true when end < 0.
478 * The range is empty when start > end or start >= length. */
479 if (start
> end
|| start
>= llen
) {
480 addReply(c
,shared
.czero
);
483 if (end
>= llen
) end
= llen
-1;
485 /* increment start and end because zsl*Rank functions
486 * use 1-based rank */
487 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
488 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
489 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,c
->argv
[1]);
490 if (deleted
) touchWatchedKey(c
->db
,c
->argv
[1]);
491 server
.dirty
+= deleted
;
492 addReplyLongLong(c
, deleted
);
500 int qsortCompareZsetopsrcByCardinality(const void *s1
, const void *s2
) {
501 zsetopsrc
*d1
= (void*) s1
, *d2
= (void*) s2
;
502 unsigned long size1
, size2
;
503 size1
= d1
->dict
? dictSize(d1
->dict
) : 0;
504 size2
= d2
->dict
? dictSize(d2
->dict
) : 0;
505 return size1
- size2
;
508 #define REDIS_AGGR_SUM 1
509 #define REDIS_AGGR_MIN 2
510 #define REDIS_AGGR_MAX 3
511 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
513 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
514 if (aggregate
== REDIS_AGGR_SUM
) {
515 *target
= *target
+ val
;
516 /* The result of adding two doubles is NaN when one variable
517 * is +inf and the other is -inf. When these numbers are added,
518 * we maintain the convention of the result being 0.0. */
519 if (isnan(*target
)) *target
= 0.0;
520 } else if (aggregate
== REDIS_AGGR_MIN
) {
521 *target
= val
< *target
? val
: *target
;
522 } else if (aggregate
== REDIS_AGGR_MAX
) {
523 *target
= val
> *target
? val
: *target
;
526 redisPanic("Unknown ZUNION/INTER aggregate type");
530 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
532 int aggregate
= REDIS_AGGR_SUM
;
536 zskiplistNode
*znode
;
541 /* expect setnum input keys to be given */
542 setnum
= atoi(c
->argv
[2]->ptr
);
545 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
549 /* test if the expected number of keys would overflow */
550 if (3+setnum
> c
->argc
) {
551 addReply(c
,shared
.syntaxerr
);
555 /* read keys to be used for input */
556 src
= zmalloc(sizeof(zsetopsrc
) * setnum
);
557 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
558 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
562 if (obj
->type
== REDIS_ZSET
) {
563 src
[i
].dict
= ((zset
*)obj
->ptr
)->dict
;
564 } else if (obj
->type
== REDIS_SET
) {
565 src
[i
].dict
= (obj
->ptr
);
568 addReply(c
,shared
.wrongtypeerr
);
573 /* default all weights to 1 */
577 /* parse optional extra arguments */
579 int remaining
= c
->argc
- j
;
582 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
584 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
585 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
586 "weight value is not a double") != REDIS_OK
)
592 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
594 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
595 aggregate
= REDIS_AGGR_SUM
;
596 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
597 aggregate
= REDIS_AGGR_MIN
;
598 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
599 aggregate
= REDIS_AGGR_MAX
;
602 addReply(c
,shared
.syntaxerr
);
608 addReply(c
,shared
.syntaxerr
);
614 /* sort sets from the smallest to largest, this will improve our
615 * algorithm's performance */
616 qsort(src
,setnum
,sizeof(zsetopsrc
),qsortCompareZsetopsrcByCardinality
);
618 dstobj
= createZsetObject();
619 dstzset
= dstobj
->ptr
;
621 if (op
== REDIS_OP_INTER
) {
622 /* skip going over all entries if the smallest zset is NULL or empty */
623 if (src
[0].dict
&& dictSize(src
[0].dict
) > 0) {
624 /* precondition: as src[0].dict is non-empty and the zsets are ordered
625 * from small to large, all src[i > 0].dict are non-empty too */
626 di
= dictGetIterator(src
[0].dict
);
627 while((de
= dictNext(di
)) != NULL
) {
630 score
= src
[0].weight
* zunionInterDictValue(de
);
631 for (j
= 1; j
< setnum
; j
++) {
632 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
634 value
= src
[j
].weight
* zunionInterDictValue(other
);
635 zunionInterAggregate(&score
, value
, aggregate
);
641 /* accept entry only when present in every source dict */
643 robj
*o
= dictGetEntryKey(de
);
644 znode
= zslInsert(dstzset
->zsl
,score
,o
);
645 incrRefCount(o
); /* added to skiplist */
646 dictAdd(dstzset
->dict
,o
,&znode
->score
);
647 incrRefCount(o
); /* added to dictionary */
650 dictReleaseIterator(di
);
652 } else if (op
== REDIS_OP_UNION
) {
653 for (i
= 0; i
< setnum
; i
++) {
654 if (!src
[i
].dict
) continue;
656 di
= dictGetIterator(src
[i
].dict
);
657 while((de
= dictNext(di
)) != NULL
) {
660 /* skip key when already processed */
661 if (dictFind(dstzset
->dict
,dictGetEntryKey(de
)) != NULL
)
663 score
= src
[i
].weight
* zunionInterDictValue(de
);
665 /* because the zsets are sorted by size, its only possible
666 * for sets at larger indices to hold this entry */
667 for (j
= (i
+1); j
< setnum
; j
++) {
668 dictEntry
*other
= dictFind(src
[j
].dict
,dictGetEntryKey(de
));
670 value
= src
[j
].weight
* zunionInterDictValue(other
);
671 zunionInterAggregate(&score
, value
, aggregate
);
675 robj
*o
= dictGetEntryKey(de
);
676 znode
= zslInsert(dstzset
->zsl
,score
,o
);
677 incrRefCount(o
); /* added to skiplist */
678 dictAdd(dstzset
->dict
,o
,&znode
->score
);
679 incrRefCount(o
); /* added to dictionary */
681 dictReleaseIterator(di
);
684 /* unknown operator */
685 redisAssert(op
== REDIS_OP_INTER
|| op
== REDIS_OP_UNION
);
688 if (dbDelete(c
->db
,dstkey
)) {
689 touchWatchedKey(c
->db
,dstkey
);
693 if (dstzset
->zsl
->length
) {
694 dbAdd(c
->db
,dstkey
,dstobj
);
695 addReplyLongLong(c
, dstzset
->zsl
->length
);
696 if (!touched
) touchWatchedKey(c
->db
,dstkey
);
699 decrRefCount(dstobj
);
700 addReply(c
, shared
.czero
);
705 void zunionstoreCommand(redisClient
*c
) {
706 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
709 void zinterstoreCommand(redisClient
*c
) {
710 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
713 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
725 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
726 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
728 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
730 } else if (c
->argc
>= 5) {
731 addReply(c
,shared
.syntaxerr
);
735 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.emptymultibulk
)) == NULL
736 || checkType(c
,o
,REDIS_ZSET
)) return;
741 /* convert negative indexes */
742 if (start
< 0) start
= llen
+start
;
743 if (end
< 0) end
= llen
+end
;
744 if (start
< 0) start
= 0;
746 /* Invariant: start >= 0, so this test will be true when end < 0.
747 * The range is empty when start > end or start >= length. */
748 if (start
> end
|| start
>= llen
) {
749 addReply(c
,shared
.emptymultibulk
);
752 if (end
>= llen
) end
= llen
-1;
753 rangelen
= (end
-start
)+1;
755 /* check if starting point is trivial, before searching
756 * the element in log(N) time */
758 ln
= start
== 0 ? zsl
->tail
: zslistTypeGetElementByRank(zsl
, llen
-start
);
761 zsl
->header
->level
[0].forward
: zslistTypeGetElementByRank(zsl
, start
+1);
764 /* Return the result in form of a multi-bulk reply */
765 addReplyMultiBulkLen(c
,withscores
? (rangelen
*2) : rangelen
);
766 for (j
= 0; j
< rangelen
; j
++) {
770 addReplyDouble(c
,ln
->score
);
771 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
775 void zrangeCommand(redisClient
*c
) {
776 zrangeGenericCommand(c
,0);
779 void zrevrangeCommand(redisClient
*c
) {
780 zrangeGenericCommand(c
,1);
783 /* This command implements both ZRANGEBYSCORE and ZCOUNT.
784 * If justcount is non-zero, just the count is returned. */
785 void genericZrangebyscoreCommand(redisClient
*c
, int justcount
) {
788 int minex
= 0, maxex
= 0; /* are min or max exclusive? */
789 int offset
= 0, limit
= -1;
793 /* Parse the min-max interval. If one of the values is prefixed
794 * by the "(" character, it's considered "open". For instance
795 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
796 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
797 if (((char*)c
->argv
[2]->ptr
)[0] == '(') {
798 min
= strtod((char*)c
->argv
[2]->ptr
+1,NULL
);
801 min
= strtod(c
->argv
[2]->ptr
,NULL
);
803 if (((char*)c
->argv
[3]->ptr
)[0] == '(') {
804 max
= strtod((char*)c
->argv
[3]->ptr
+1,NULL
);
807 max
= strtod(c
->argv
[3]->ptr
,NULL
);
810 /* Parse "WITHSCORES": note that if the command was called with
811 * the name ZCOUNT then we are sure that c->argc == 4, so we'll never
812 * enter the following paths to parse WITHSCORES and LIMIT. */
813 if (c
->argc
== 5 || c
->argc
== 8) {
814 if (strcasecmp(c
->argv
[c
->argc
-1]->ptr
,"withscores") == 0)
819 if (c
->argc
!= (4 + withscores
) && c
->argc
!= (7 + withscores
))
822 addReplyError(c
,"wrong number of arguments for ZRANGEBYSCORE");
827 if (c
->argc
== (7 + withscores
) && strcasecmp(c
->argv
[4]->ptr
,"limit")) {
828 addReply(c
,shared
.syntaxerr
);
830 } else if (c
->argc
== (7 + withscores
)) {
831 offset
= atoi(c
->argv
[5]->ptr
);
832 limit
= atoi(c
->argv
[6]->ptr
);
833 if (offset
< 0) offset
= 0;
836 /* Ok, lookup the key and get the range */
837 o
= lookupKeyRead(c
->db
,c
->argv
[1]);
839 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
841 if (o
->type
!= REDIS_ZSET
) {
842 addReply(c
,shared
.wrongtypeerr
);
844 zset
*zsetobj
= o
->ptr
;
845 zskiplist
*zsl
= zsetobj
->zsl
;
848 void *replylen
= NULL
;
849 unsigned long rangelen
= 0;
851 /* Get the first node with the score >= min, or with
852 * score > min if 'minex' is true. */
853 ln
= zslFirstWithScore(zsl
,min
);
854 while (minex
&& ln
&& ln
->score
== min
) ln
= ln
->level
[0].forward
;
857 /* No element matching the speciifed interval */
858 addReply(c
,justcount
? shared
.czero
: shared
.emptymultibulk
);
862 /* We don't know in advance how many matching elements there
863 * are in the list, so we push this object that will represent
864 * the multi-bulk length in the output buffer, and will "fix"
867 replylen
= addDeferredMultiBulkLength(c
);
869 while(ln
&& (maxex
? (ln
->score
< max
) : (ln
->score
<= max
))) {
872 ln
= ln
->level
[0].forward
;
875 if (limit
== 0) break;
880 addReplyDouble(c
,ln
->score
);
882 ln
= ln
->level
[0].forward
;
884 if (limit
> 0) limit
--;
887 addReplyLongLong(c
,(long)rangelen
);
889 setDeferredMultiBulkLength(c
,replylen
,
890 withscores
? (rangelen
*2) : rangelen
);
896 void zrangebyscoreCommand(redisClient
*c
) {
897 genericZrangebyscoreCommand(c
,0);
900 void zcountCommand(redisClient
*c
) {
901 genericZrangebyscoreCommand(c
,1);
904 void zcardCommand(redisClient
*c
) {
908 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.czero
)) == NULL
||
909 checkType(c
,o
,REDIS_ZSET
)) return;
912 addReplyLongLong(c
,zs
->zsl
->length
);
915 void zscoreCommand(redisClient
*c
) {
920 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
921 checkType(c
,o
,REDIS_ZSET
)) return;
924 de
= dictFind(zs
->dict
,c
->argv
[2]);
926 addReply(c
,shared
.nullbulk
);
928 double *score
= dictGetEntryVal(de
);
930 addReplyDouble(c
,*score
);
934 void zrankGenericCommand(redisClient
*c
, int reverse
) {
942 if ((o
= lookupKeyReadOrReply(c
,c
->argv
[1],shared
.nullbulk
)) == NULL
||
943 checkType(c
,o
,REDIS_ZSET
)) return;
947 de
= dictFind(zs
->dict
,c
->argv
[2]);
949 addReply(c
,shared
.nullbulk
);
953 score
= dictGetEntryVal(de
);
954 rank
= zslistTypeGetRank(zsl
, *score
, c
->argv
[2]);
957 addReplyLongLong(c
, zsl
->length
- rank
);
959 addReplyLongLong(c
, rank
-1);
962 addReply(c
,shared
.nullbulk
);
966 void zrankCommand(redisClient
*c
) {
967 zrankGenericCommand(c
, 0);
970 void zrevrankCommand(redisClient
*c
) {
971 zrankGenericCommand(c
, 1);