]>
git.saurik.com Git - redis.git/blob - src/t_zset.c
63657890974343f860017d76a80264368a07e953
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 /* Struct to hold a inclusive/exclusive range spec. */
180 int minex
, maxex
; /* are min or max exclusive? */
183 static int zslValueGteMin(double value
, zrangespec
*spec
) {
184 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
187 static int zslValueLteMax(double value
, zrangespec
*spec
) {
188 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
191 /* Returns if there is a part of the zset is in range. */
192 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
195 /* Test for ranges that will always be empty. */
196 if (range
->min
> range
->max
||
197 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
200 if (x
== NULL
|| !zslValueGteMin(x
->score
,range
))
202 x
= zsl
->header
->level
[0].forward
;
203 if (x
== NULL
|| !zslValueLteMax(x
->score
,range
))
208 /* Find the first node that is contained in the specified range.
209 * Returns NULL when no element is contained in the range. */
210 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
214 /* If everything is out of range, return early. */
215 if (!zslIsInRange(zsl
,&range
)) return NULL
;
218 for (i
= zsl
->level
-1; i
>= 0; i
--) {
219 /* Go forward while *OUT* of range. */
220 while (x
->level
[i
].forward
&&
221 !zslValueGteMin(x
->level
[i
].forward
->score
,&range
))
222 x
= x
->level
[i
].forward
;
225 /* This is an inner range, so the next node cannot be NULL. */
226 x
= x
->level
[0].forward
;
227 redisAssert(x
!= NULL
);
229 /* Check if score <= max. */
230 if (!zslValueLteMax(x
->score
,&range
)) return NULL
;
234 /* Find the last node that is contained in the specified range.
235 * Returns NULL when no element is contained in the range. */
236 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
240 /* If everything is out of range, return early. */
241 if (!zslIsInRange(zsl
,&range
)) return NULL
;
244 for (i
= zsl
->level
-1; i
>= 0; i
--) {
245 /* Go forward while *IN* range. */
246 while (x
->level
[i
].forward
&&
247 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
248 x
= x
->level
[i
].forward
;
251 /* This is an inner range, so this node cannot be NULL. */
252 redisAssert(x
!= NULL
);
254 /* Check if score >= min. */
255 if (!zslValueGteMin(x
->score
,&range
)) return NULL
;
259 /* Delete all the elements with score between min and max from the skiplist.
260 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
261 * Note that this function takes the reference to the hash table view of the
262 * sorted set, in order to remove the elements from the hash table too. */
263 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
264 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
265 unsigned long removed
= 0;
269 for (i
= zsl
->level
-1; i
>= 0; i
--) {
270 while (x
->level
[i
].forward
&& (range
.minex
?
271 x
->level
[i
].forward
->score
<= range
.min
:
272 x
->level
[i
].forward
->score
< range
.min
))
273 x
= x
->level
[i
].forward
;
277 /* Current node is the last with score < or <= min. */
278 x
= x
->level
[0].forward
;
280 /* Delete nodes while in range. */
281 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
282 zskiplistNode
*next
= x
->level
[0].forward
;
283 zslDeleteNode(zsl
,x
,update
);
284 dictDelete(dict
,x
->obj
);
292 /* Delete all the elements with rank between start and end from the skiplist.
293 * Start and end are inclusive. Note that start and end need to be 1-based */
294 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
295 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
296 unsigned long traversed
= 0, removed
= 0;
300 for (i
= zsl
->level
-1; i
>= 0; i
--) {
301 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
302 traversed
+= x
->level
[i
].span
;
303 x
= x
->level
[i
].forward
;
309 x
= x
->level
[0].forward
;
310 while (x
&& traversed
<= end
) {
311 zskiplistNode
*next
= x
->level
[0].forward
;
312 zslDeleteNode(zsl
,x
,update
);
313 dictDelete(dict
,x
->obj
);
322 /* Find the rank for an element by both score and key.
323 * Returns 0 when the element cannot be found, rank otherwise.
324 * Note that the rank is 1-based due to the span of zsl->header to the
326 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
328 unsigned long rank
= 0;
332 for (i
= zsl
->level
-1; i
>= 0; i
--) {
333 while (x
->level
[i
].forward
&&
334 (x
->level
[i
].forward
->score
< score
||
335 (x
->level
[i
].forward
->score
== score
&&
336 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
337 rank
+= x
->level
[i
].span
;
338 x
= x
->level
[i
].forward
;
341 /* x might be equal to zsl->header, so test if obj is non-NULL */
342 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
349 /* Finds an element by its rank. The rank argument needs to be 1-based. */
350 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
352 unsigned long traversed
= 0;
356 for (i
= zsl
->level
-1; i
>= 0; i
--) {
357 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
359 traversed
+= x
->level
[i
].span
;
360 x
= x
->level
[i
].forward
;
362 if (traversed
== rank
) {
369 /* Populate the rangespec according to the objects min and max. */
370 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
372 spec
->minex
= spec
->maxex
= 0;
374 /* Parse the min-max interval. If one of the values is prefixed
375 * by the "(" character, it's considered "open". For instance
376 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
377 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
378 if (min
->encoding
== REDIS_ENCODING_INT
) {
379 spec
->min
= (long)min
->ptr
;
381 if (((char*)min
->ptr
)[0] == '(') {
382 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
383 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
386 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
387 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
390 if (max
->encoding
== REDIS_ENCODING_INT
) {
391 spec
->max
= (long)max
->ptr
;
393 if (((char*)max
->ptr
)[0] == '(') {
394 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
395 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
398 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
399 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
406 /*-----------------------------------------------------------------------------
407 * Ziplist-backed sorted set API
408 *----------------------------------------------------------------------------*/
410 double zzlGetScore(unsigned char *sptr
) {
417 redisAssert(sptr
!= NULL
);
418 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
421 memcpy(buf
,vstr
,vlen
);
423 score
= strtod(buf
,NULL
);
431 /* Compare element in sorted set with given element. */
432 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
436 unsigned char vbuf
[32];
439 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
441 /* Store string representation of long long in buf. */
442 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
446 minlen
= (vlen
< clen
) ? vlen
: clen
;
447 cmp
= memcmp(vstr
,cstr
,minlen
);
448 if (cmp
== 0) return vlen
-clen
;
452 unsigned int zzlLength(unsigned char *zl
) {
453 return ziplistLen(zl
)/2;
456 /* Move to next entry based on the values in eptr and sptr. Both are set to
457 * NULL when there is no next entry. */
458 void zzlNext(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
459 unsigned char *_eptr
, *_sptr
;
460 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
462 _eptr
= ziplistNext(zl
,*sptr
);
464 _sptr
= ziplistNext(zl
,_eptr
);
465 redisAssert(_sptr
!= NULL
);
475 /* Move to the previous entry based on the values in eptr and sptr. Both are
476 * set to NULL when there is no next entry. */
477 void zzlPrev(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
478 unsigned char *_eptr
, *_sptr
;
479 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
481 _sptr
= ziplistPrev(zl
,*eptr
);
483 _eptr
= ziplistPrev(zl
,_sptr
);
484 redisAssert(_eptr
!= NULL
);
486 /* No previous entry. */
494 /* Returns if there is a part of the zset is in range. Should only be used
495 * internally by zzlFirstInRange and zzlLastInRange. */
496 int zzlIsInRange(unsigned char *zl
, zrangespec
*range
) {
500 /* Test for ranges that will always be empty. */
501 if (range
->min
> range
->max
||
502 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
505 p
= ziplistIndex(zl
,-1); /* Last score. */
506 redisAssert(p
!= NULL
);
507 score
= zzlGetScore(p
);
508 if (!zslValueGteMin(score
,range
))
511 p
= ziplistIndex(zl
,1); /* First score. */
512 redisAssert(p
!= NULL
);
513 score
= zzlGetScore(p
);
514 if (!zslValueLteMax(score
,range
))
520 /* Find pointer to the first element contained in the specified range.
521 * Returns NULL when no element is contained in the range. */
522 unsigned char *zzlFirstInRange(unsigned char *zl
, zrangespec range
) {
523 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
526 /* If everything is out of range, return early. */
527 if (!zzlIsInRange(zl
,&range
)) return NULL
;
529 while (eptr
!= NULL
) {
530 sptr
= ziplistNext(zl
,eptr
);
531 redisAssert(sptr
!= NULL
);
533 score
= zzlGetScore(sptr
);
534 if (zslValueGteMin(score
,&range
)) {
535 /* Check if score <= max. */
536 if (zslValueLteMax(score
,&range
))
541 /* Move to next element. */
542 eptr
= ziplistNext(zl
,sptr
);
548 /* Find pointer to the last element contained in the specified range.
549 * Returns NULL when no element is contained in the range. */
550 unsigned char *zzlLastInRange(unsigned char *zl
, zrangespec range
) {
551 unsigned char *eptr
= ziplistIndex(zl
,-2), *sptr
;
554 /* If everything is out of range, return early. */
555 if (!zzlIsInRange(zl
,&range
)) return NULL
;
557 while (eptr
!= NULL
) {
558 sptr
= ziplistNext(zl
,eptr
);
559 redisAssert(sptr
!= NULL
);
561 score
= zzlGetScore(sptr
);
562 if (zslValueLteMax(score
,&range
)) {
563 /* Check if score >= min. */
564 if (zslValueGteMin(score
,&range
))
569 /* Move to previous element by moving to the score of previous element.
570 * When this returns NULL, we know there also is no element. */
571 sptr
= ziplistPrev(zl
,eptr
);
573 redisAssert((eptr
= ziplistPrev(zl
,sptr
)) != NULL
);
581 unsigned char *zzlFind(unsigned char *zl
, robj
*ele
, double *score
) {
582 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
584 ele
= getDecodedObject(ele
);
585 while (eptr
!= NULL
) {
586 sptr
= ziplistNext(zl
,eptr
);
587 redisAssert(sptr
!= NULL
);
589 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
590 /* Matching element, pull out score. */
591 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
596 /* Move to next element. */
597 eptr
= ziplistNext(zl
,sptr
);
604 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
605 * don't want to modify the one given as argument. */
606 unsigned char *zzlDelete(unsigned char *zl
, unsigned char *eptr
) {
607 unsigned char *p
= eptr
;
609 /* TODO: add function to ziplist API to delete N elements from offset. */
610 zl
= ziplistDelete(zl
,&p
);
611 zl
= ziplistDelete(zl
,&p
);
615 unsigned char *zzlInsertAt(unsigned char *zl
, unsigned char *eptr
, robj
*ele
, double score
) {
621 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
622 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
624 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
625 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
627 /* Keep offset relative to zl, as it might be re-allocated. */
629 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
632 /* Insert score after the element. */
633 redisAssert((sptr
= ziplistNext(zl
,eptr
)) != NULL
);
634 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
640 /* Insert (element,score) pair in ziplist. This function assumes the element is
641 * not yet present in the list. */
642 unsigned char *zzlInsert(unsigned char *zl
, robj
*ele
, double score
) {
643 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
646 ele
= getDecodedObject(ele
);
647 while (eptr
!= NULL
) {
648 sptr
= ziplistNext(zl
,eptr
);
649 redisAssert(sptr
!= NULL
);
650 s
= zzlGetScore(sptr
);
653 /* First element with score larger than score for element to be
654 * inserted. This means we should take its spot in the list to
655 * maintain ordering. */
656 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
658 } else if (s
== score
) {
659 /* Ensure lexicographical ordering for elements. */
660 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) > 0) {
661 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
666 /* Move to next element. */
667 eptr
= ziplistNext(zl
,sptr
);
670 /* Push on tail of list when it was not yet inserted. */
672 zl
= zzlInsertAt(zl
,NULL
,ele
,score
);
678 unsigned char *zzlDeleteRangeByScore(unsigned char *zl
, zrangespec range
, unsigned long *deleted
) {
679 unsigned char *eptr
, *sptr
;
681 unsigned long num
= 0;
683 if (deleted
!= NULL
) *deleted
= 0;
685 eptr
= zzlFirstInRange(zl
,range
);
686 if (eptr
== NULL
) return zl
;
688 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
689 * byte and ziplistNext will return NULL. */
690 while ((sptr
= ziplistNext(zl
,eptr
)) != NULL
) {
691 score
= zzlGetScore(sptr
);
692 if (zslValueLteMax(score
,&range
)) {
693 /* Delete both the element and the score. */
694 zl
= ziplistDelete(zl
,&eptr
);
695 zl
= ziplistDelete(zl
,&eptr
);
698 /* No longer in range. */
703 if (deleted
!= NULL
) *deleted
= num
;
707 /* Delete all the elements with rank between start and end from the skiplist.
708 * Start and end are inclusive. Note that start and end need to be 1-based */
709 unsigned char *zzlDeleteRangeByRank(unsigned char *zl
, unsigned int start
, unsigned int end
, unsigned long *deleted
) {
710 unsigned int num
= (end
-start
)+1;
711 if (deleted
) *deleted
= num
;
712 zl
= ziplistDeleteRange(zl
,2*(start
-1),2*num
);
716 /*-----------------------------------------------------------------------------
717 * Common sorted set API
718 *----------------------------------------------------------------------------*/
720 unsigned int zsetLength(robj
*zobj
) {
722 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
723 length
= zzlLength(zobj
->ptr
);
724 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
725 length
= ((zset
*)zobj
->ptr
)->zsl
->length
;
727 redisPanic("Unknown sorted set encoding");
732 void zsetConvert(robj
*zobj
, int encoding
) {
734 zskiplistNode
*node
, *next
;
738 if (zobj
->encoding
== encoding
) return;
739 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
740 unsigned char *zl
= zobj
->ptr
;
741 unsigned char *eptr
, *sptr
;
746 if (encoding
!= REDIS_ENCODING_RAW
)
747 redisPanic("Unknown target encoding");
749 zs
= zmalloc(sizeof(*zs
));
750 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
751 zs
->zsl
= zslCreate();
753 eptr
= ziplistIndex(zl
,0);
754 redisAssert(eptr
!= NULL
);
755 sptr
= ziplistNext(zl
,eptr
);
756 redisAssert(sptr
!= NULL
);
758 while (eptr
!= NULL
) {
759 score
= zzlGetScore(sptr
);
760 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
762 ele
= createStringObjectFromLongLong(vlong
);
764 ele
= createStringObject((char*)vstr
,vlen
);
766 /* Has incremented refcount since it was just created. */
767 node
= zslInsert(zs
->zsl
,score
,ele
);
768 redisAssert(dictAdd(zs
->dict
,ele
,&node
->score
) == DICT_OK
);
769 incrRefCount(ele
); /* Added to dictionary. */
770 zzlNext(zl
,&eptr
,&sptr
);
775 zobj
->encoding
= REDIS_ENCODING_RAW
;
776 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
777 unsigned char *zl
= ziplistNew();
779 if (encoding
!= REDIS_ENCODING_ZIPLIST
)
780 redisPanic("Unknown target encoding");
782 /* Approach similar to zslFree(), since we want to free the skiplist at
783 * the same time as creating the ziplist. */
785 dictRelease(zs
->dict
);
786 node
= zs
->zsl
->header
->level
[0].forward
;
787 zfree(zs
->zsl
->header
);
791 ele
= getDecodedObject(node
->obj
);
792 zl
= zzlInsertAt(zl
,NULL
,ele
,node
->score
);
795 next
= node
->level
[0].forward
;
802 zobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
804 redisPanic("Unknown sorted set encoding");
808 /*-----------------------------------------------------------------------------
809 * Sorted set commands
810 *----------------------------------------------------------------------------*/
812 /* This generic command implements both ZADD and ZINCRBY. */
813 void zaddGenericCommand(redisClient
*c
, int incr
) {
814 static char *nanerr
= "resulting score is not a number (NaN)";
815 robj
*key
= c
->argv
[1];
819 double score
, curscore
= 0.0;
821 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&score
,NULL
) != REDIS_OK
)
824 zobj
= lookupKeyWrite(c
->db
,key
);
826 if (server
.zset_max_ziplist_entries
== 0 ||
827 server
.zset_max_ziplist_value
< sdslen(c
->argv
[3]->ptr
))
829 zobj
= createZsetObject();
831 zobj
= createZsetZiplistObject();
833 dbAdd(c
->db
,key
,zobj
);
835 if (zobj
->type
!= REDIS_ZSET
) {
836 addReply(c
,shared
.wrongtypeerr
);
841 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
844 /* Prefer non-encoded element when dealing with ziplists. */
846 if ((eptr
= zzlFind(zobj
->ptr
,ele
,&curscore
)) != NULL
) {
850 addReplyError(c
,nanerr
);
851 /* Don't need to check if the sorted set is empty, because
852 * we know it has at least one element. */
857 /* Remove and re-insert when score changed. */
858 if (score
!= curscore
) {
859 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
860 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
862 signalModifiedKey(c
->db
,key
);
866 if (incr
) /* ZINCRBY */
867 addReplyDouble(c
,score
);
869 addReply(c
,shared
.czero
);
871 /* Optimize: check if the element is too large or the list becomes
872 * too long *before* executing zzlInsert. */
873 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
874 if (zzlLength(zobj
->ptr
) > server
.zset_max_ziplist_entries
)
875 zsetConvert(zobj
,REDIS_ENCODING_RAW
);
876 if (sdslen(ele
->ptr
) > server
.zset_max_ziplist_value
)
877 zsetConvert(zobj
,REDIS_ENCODING_RAW
);
879 signalModifiedKey(c
->db
,key
);
882 if (incr
) /* ZINCRBY */
883 addReplyDouble(c
,score
);
885 addReply(c
,shared
.cone
);
887 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
888 zset
*zs
= zobj
->ptr
;
889 zskiplistNode
*znode
;
892 ele
= c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
893 de
= dictFind(zs
->dict
,ele
);
895 curobj
= dictGetEntryKey(de
);
896 curscore
= *(double*)dictGetEntryVal(de
);
901 addReplyError(c
,nanerr
);
902 /* Don't need to check if the sorted set is empty, because
903 * we know it has at least one element. */
908 /* Remove and re-insert when score changed. We can safely delete
909 * the key object from the skiplist, since the dictionary still has
910 * a reference to it. */
911 if (score
!= curscore
) {
912 redisAssert(zslDelete(zs
->zsl
,curscore
,curobj
));
913 znode
= zslInsert(zs
->zsl
,score
,curobj
);
914 incrRefCount(curobj
); /* Re-inserted in skiplist. */
915 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
917 signalModifiedKey(c
->db
,key
);
921 if (incr
) /* ZINCRBY */
922 addReplyDouble(c
,score
);
924 addReply(c
,shared
.czero
);
926 znode
= zslInsert(zs
->zsl
,score
,ele
);
927 incrRefCount(ele
); /* Inserted in skiplist. */
928 redisAssert(dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
929 incrRefCount(ele
); /* Added to dictionary. */
931 signalModifiedKey(c
->db
,key
);
934 if (incr
) /* ZINCRBY */
935 addReplyDouble(c
,score
);
937 addReply(c
,shared
.cone
);
940 redisPanic("Unknown sorted set encoding");
944 void zaddCommand(redisClient
*c
) {
945 zaddGenericCommand(c
,0);
948 void zincrbyCommand(redisClient
*c
) {
949 zaddGenericCommand(c
,1);
952 void zremCommand(redisClient
*c
) {
953 robj
*key
= c
->argv
[1];
954 robj
*ele
= c
->argv
[2];
957 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
958 checkType(c
,zobj
,REDIS_ZSET
)) return;
960 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
963 if ((eptr
= zzlFind(zobj
->ptr
,ele
,NULL
)) != NULL
) {
964 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
965 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
967 addReply(c
,shared
.czero
);
970 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
971 zset
*zs
= zobj
->ptr
;
975 de
= dictFind(zs
->dict
,ele
);
977 /* Delete from the skiplist */
978 score
= *(double*)dictGetEntryVal(de
);
979 redisAssert(zslDelete(zs
->zsl
,score
,ele
));
981 /* Delete from the hash table */
982 dictDelete(zs
->dict
,ele
);
983 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
984 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
986 addReply(c
,shared
.czero
);
990 redisPanic("Unknown sorted set encoding");
993 signalModifiedKey(c
->db
,key
);
995 addReply(c
,shared
.cone
);
998 void zremrangebyscoreCommand(redisClient
*c
) {
999 robj
*key
= c
->argv
[1];
1002 unsigned long deleted
;
1004 /* Parse the range arguments. */
1005 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1006 addReplyError(c
,"min or max is not a double");
1010 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1011 checkType(c
,zobj
,REDIS_ZSET
)) return;
1013 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1014 zobj
->ptr
= zzlDeleteRangeByScore(zobj
->ptr
,range
,&deleted
);
1015 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1016 zset
*zs
= zobj
->ptr
;
1017 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1018 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1019 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1021 redisPanic("Unknown sorted set encoding");
1024 if (deleted
) signalModifiedKey(c
->db
,key
);
1025 server
.dirty
+= deleted
;
1026 addReplyLongLong(c
,deleted
);
1029 void zremrangebyrankCommand(redisClient
*c
) {
1030 robj
*key
= c
->argv
[1];
1035 unsigned long deleted
;
1037 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1038 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1040 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1041 checkType(c
,zobj
,REDIS_ZSET
)) return;
1043 /* Sanitize indexes. */
1044 llen
= zsetLength(zobj
);
1045 if (start
< 0) start
= llen
+start
;
1046 if (end
< 0) end
= llen
+end
;
1047 if (start
< 0) start
= 0;
1049 /* Invariant: start >= 0, so this test will be true when end < 0.
1050 * The range is empty when start > end or start >= length. */
1051 if (start
> end
|| start
>= llen
) {
1052 addReply(c
,shared
.czero
);
1055 if (end
>= llen
) end
= llen
-1;
1057 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1058 /* Correct for 1-based rank. */
1059 zobj
->ptr
= zzlDeleteRangeByRank(zobj
->ptr
,start
+1,end
+1,&deleted
);
1060 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1061 zset
*zs
= zobj
->ptr
;
1063 /* Correct for 1-based rank. */
1064 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1065 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1066 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1068 redisPanic("Unknown sorted set encoding");
1071 if (deleted
) signalModifiedKey(c
->db
,key
);
1072 server
.dirty
+= deleted
;
1073 addReplyLongLong(c
,deleted
);
1078 int type
; /* Set, sorted set */
1083 /* Set iterators. */
1096 /* Sorted set iterators. */
1100 unsigned char *eptr
, *sptr
;
1104 zskiplistNode
*node
;
1111 /* Use dirty flags for pointers that need to be cleaned up in the next
1112 * iteration over the zsetopval. The dirty flag for the long long value is
1113 * special, since long long values don't need cleanup. Instead, it means that
1114 * we already checked that "ell" holds a long long, or tried to convert another
1115 * representation into a long long value. When this was successful,
1116 * OPVAL_VALID_LL is set as well. */
1117 #define OPVAL_DIRTY_ROBJ 1
1118 #define OPVAL_DIRTY_LL 2
1119 #define OPVAL_VALID_LL 4
1121 /* Store value retrieved from the iterator. */
1124 unsigned char _buf
[32]; /* Private buffer. */
1126 unsigned char *estr
;
1132 typedef union _iterset iterset
;
1133 typedef union _iterzset iterzset
;
1135 void zuiInitIterator(zsetopsrc
*op
) {
1136 if (op
->subject
== NULL
)
1139 if (op
->type
== REDIS_SET
) {
1140 iterset
*it
= &op
->iter
.set
;
1141 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1142 it
->is
.is
= op
->subject
->ptr
;
1144 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1145 it
->ht
.dict
= op
->subject
->ptr
;
1146 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1147 it
->ht
.de
= dictNext(it
->ht
.di
);
1149 redisPanic("Unknown set encoding");
1151 } else if (op
->type
== REDIS_ZSET
) {
1152 iterzset
*it
= &op
->iter
.zset
;
1153 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1154 it
->zl
.zl
= op
->subject
->ptr
;
1155 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1156 if (it
->zl
.eptr
!= NULL
) {
1157 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1158 redisAssert(it
->zl
.sptr
!= NULL
);
1160 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1161 it
->sl
.zs
= op
->subject
->ptr
;
1162 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1164 redisPanic("Unknown sorted set encoding");
1167 redisPanic("Unsupported type");
1171 void zuiClearIterator(zsetopsrc
*op
) {
1172 if (op
->subject
== NULL
)
1175 if (op
->type
== REDIS_SET
) {
1176 iterset
*it
= &op
->iter
.set
;
1177 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1178 REDIS_NOTUSED(it
); /* skip */
1179 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1180 dictReleaseIterator(it
->ht
.di
);
1182 redisPanic("Unknown set encoding");
1184 } else if (op
->type
== REDIS_ZSET
) {
1185 iterzset
*it
= &op
->iter
.zset
;
1186 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1187 REDIS_NOTUSED(it
); /* skip */
1188 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1189 REDIS_NOTUSED(it
); /* skip */
1191 redisPanic("Unknown sorted set encoding");
1194 redisPanic("Unsupported type");
1198 int zuiLength(zsetopsrc
*op
) {
1199 if (op
->subject
== NULL
)
1202 if (op
->type
== REDIS_SET
) {
1203 iterset
*it
= &op
->iter
.set
;
1204 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1205 return intsetLen(it
->is
.is
);
1206 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1207 return dictSize(it
->ht
.dict
);
1209 redisPanic("Unknown set encoding");
1211 } else if (op
->type
== REDIS_ZSET
) {
1212 iterzset
*it
= &op
->iter
.zset
;
1213 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1214 return zzlLength(it
->zl
.zl
);
1215 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1216 return it
->sl
.zs
->zsl
->length
;
1218 redisPanic("Unknown sorted set encoding");
1221 redisPanic("Unsupported type");
1225 /* Check if the current value is valid. If so, store it in the passed structure
1226 * and move to the next element. If not valid, this means we have reached the
1227 * end of the structure and can abort. */
1228 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1229 if (op
->subject
== NULL
)
1232 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1233 decrRefCount(val
->ele
);
1235 bzero(val
,sizeof(zsetopval
));
1237 if (op
->type
== REDIS_SET
) {
1238 iterset
*it
= &op
->iter
.set
;
1239 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1240 if (!intsetGet(it
->is
.is
,it
->is
.ii
,&val
->ell
))
1244 /* Move to next element. */
1246 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1247 if (it
->ht
.de
== NULL
)
1249 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1252 /* Move to next element. */
1253 it
->ht
.de
= dictNext(it
->ht
.di
);
1255 redisPanic("Unknown set encoding");
1257 } else if (op
->type
== REDIS_ZSET
) {
1258 iterzset
*it
= &op
->iter
.zset
;
1259 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1260 /* No need to check both, but better be explicit. */
1261 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1263 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1264 val
->score
= zzlGetScore(it
->zl
.sptr
);
1266 /* Move to next element. */
1267 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1268 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1269 if (it
->sl
.node
== NULL
)
1271 val
->ele
= it
->sl
.node
->obj
;
1272 val
->score
= it
->sl
.node
->score
;
1274 /* Move to next element. */
1275 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1277 redisPanic("Unknown sorted set encoding");
1280 redisPanic("Unsupported type");
1285 int zuiLongLongFromValue(zsetopval
*val
) {
1286 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1287 val
->flags
|= OPVAL_DIRTY_LL
;
1289 if (val
->ele
!= NULL
) {
1290 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1291 val
->ell
= (long)val
->ele
->ptr
;
1292 val
->flags
|= OPVAL_VALID_LL
;
1293 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1294 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1295 val
->flags
|= OPVAL_VALID_LL
;
1297 redisPanic("Unsupported element encoding");
1299 } else if (val
->estr
!= NULL
) {
1300 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1301 val
->flags
|= OPVAL_VALID_LL
;
1303 /* The long long was already set, flag as valid. */
1304 val
->flags
|= OPVAL_VALID_LL
;
1307 return val
->flags
& OPVAL_VALID_LL
;
1310 robj
*zuiObjectFromValue(zsetopval
*val
) {
1311 if (val
->ele
== NULL
) {
1312 if (val
->estr
!= NULL
) {
1313 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1315 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1317 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1322 int zuiBufferFromValue(zsetopval
*val
) {
1323 if (val
->estr
== NULL
) {
1324 if (val
->ele
!= NULL
) {
1325 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1326 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1327 val
->estr
= val
->_buf
;
1328 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1329 val
->elen
= sdslen(val
->ele
->ptr
);
1330 val
->estr
= val
->ele
->ptr
;
1332 redisPanic("Unsupported element encoding");
1335 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1336 val
->estr
= val
->_buf
;
1342 /* Find value pointed to by val in the source pointer to by op. When found,
1343 * return 1 and store its score in target. Return 0 otherwise. */
1344 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1345 if (op
->subject
== NULL
)
1348 if (op
->type
== REDIS_SET
) {
1349 iterset
*it
= &op
->iter
.set
;
1351 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1352 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1358 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1359 zuiObjectFromValue(val
);
1360 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1367 redisPanic("Unknown set encoding");
1369 } else if (op
->type
== REDIS_ZSET
) {
1370 iterzset
*it
= &op
->iter
.zset
;
1371 zuiObjectFromValue(val
);
1373 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1374 if (zzlFind(it
->zl
.zl
,val
->ele
,score
) != NULL
) {
1375 /* Score is already set by zzlFind. */
1380 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1382 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1383 *score
= *(double*)dictGetEntryVal(de
);
1389 redisPanic("Unknown sorted set encoding");
1392 redisPanic("Unsupported type");
1396 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1397 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1400 #define REDIS_AGGR_SUM 1
1401 #define REDIS_AGGR_MIN 2
1402 #define REDIS_AGGR_MAX 3
1403 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1405 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1406 if (aggregate
== REDIS_AGGR_SUM
) {
1407 *target
= *target
+ val
;
1408 /* The result of adding two doubles is NaN when one variable
1409 * is +inf and the other is -inf. When these numbers are added,
1410 * we maintain the convention of the result being 0.0. */
1411 if (isnan(*target
)) *target
= 0.0;
1412 } else if (aggregate
== REDIS_AGGR_MIN
) {
1413 *target
= val
< *target
? val
: *target
;
1414 } else if (aggregate
== REDIS_AGGR_MAX
) {
1415 *target
= val
> *target
? val
: *target
;
1418 redisPanic("Unknown ZUNION/INTER aggregate type");
1422 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1424 int aggregate
= REDIS_AGGR_SUM
;
1428 unsigned int maxelelen
= 0;
1431 zskiplistNode
*znode
;
1434 /* expect setnum input keys to be given */
1435 setnum
= atoi(c
->argv
[2]->ptr
);
1438 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1442 /* test if the expected number of keys would overflow */
1443 if (3+setnum
> c
->argc
) {
1444 addReply(c
,shared
.syntaxerr
);
1448 /* read keys to be used for input */
1449 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1450 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1451 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1453 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1455 addReply(c
,shared
.wrongtypeerr
);
1459 src
[i
].subject
= obj
;
1460 src
[i
].type
= obj
->type
;
1461 src
[i
].encoding
= obj
->encoding
;
1463 src
[i
].subject
= NULL
;
1466 /* Default all weights to 1. */
1467 src
[i
].weight
= 1.0;
1470 /* parse optional extra arguments */
1472 int remaining
= c
->argc
- j
;
1475 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1477 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1478 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1479 "weight value is not a double") != REDIS_OK
)
1485 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1487 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1488 aggregate
= REDIS_AGGR_SUM
;
1489 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1490 aggregate
= REDIS_AGGR_MIN
;
1491 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1492 aggregate
= REDIS_AGGR_MAX
;
1495 addReply(c
,shared
.syntaxerr
);
1501 addReply(c
,shared
.syntaxerr
);
1507 for (i
= 0; i
< setnum
; i
++)
1508 zuiInitIterator(&src
[i
]);
1510 /* sort sets from the smallest to largest, this will improve our
1511 * algorithm's performance */
1512 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1514 dstobj
= createZsetObject();
1515 dstzset
= dstobj
->ptr
;
1517 if (op
== REDIS_OP_INTER
) {
1518 /* Skip everything if the smallest input is empty. */
1519 if (zuiLength(&src
[0]) > 0) {
1520 /* Precondition: as src[0] is non-empty and the inputs are ordered
1521 * by size, all src[i > 0] are non-empty too. */
1522 while (zuiNext(&src
[0],&zval
)) {
1523 double score
, value
;
1525 score
= src
[0].weight
* zval
.score
;
1526 for (j
= 1; j
< setnum
; j
++) {
1527 if (zuiFind(&src
[j
],&zval
,&value
)) {
1528 value
*= src
[j
].weight
;
1529 zunionInterAggregate(&score
,value
,aggregate
);
1535 /* Only continue when present in every input. */
1537 tmp
= zuiObjectFromValue(&zval
);
1538 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1539 incrRefCount(tmp
); /* added to skiplist */
1540 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1541 incrRefCount(tmp
); /* added to dictionary */
1543 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1544 if (sdslen(tmp
->ptr
) > maxelelen
)
1545 maxelelen
= sdslen(tmp
->ptr
);
1549 } else if (op
== REDIS_OP_UNION
) {
1550 for (i
= 0; i
< setnum
; i
++) {
1551 if (zuiLength(&src
[0]) == 0)
1554 while (zuiNext(&src
[i
],&zval
)) {
1555 double score
, value
;
1557 /* Skip key when already processed */
1558 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1561 /* Initialize score */
1562 score
= src
[i
].weight
* zval
.score
;
1564 /* Because the inputs are sorted by size, it's only possible
1565 * for sets at larger indices to hold this element. */
1566 for (j
= (i
+1); j
< setnum
; j
++) {
1567 if (zuiFind(&src
[j
],&zval
,&value
)) {
1568 value
*= src
[j
].weight
;
1569 zunionInterAggregate(&score
,value
,aggregate
);
1573 tmp
= zuiObjectFromValue(&zval
);
1574 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1575 incrRefCount(zval
.ele
); /* added to skiplist */
1576 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1577 incrRefCount(zval
.ele
); /* added to dictionary */
1579 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1580 if (sdslen(tmp
->ptr
) > maxelelen
)
1581 maxelelen
= sdslen(tmp
->ptr
);
1585 redisPanic("Unknown operator");
1588 for (i
= 0; i
< setnum
; i
++)
1589 zuiClearIterator(&src
[i
]);
1591 if (dbDelete(c
->db
,dstkey
)) {
1592 signalModifiedKey(c
->db
,dstkey
);
1596 if (dstzset
->zsl
->length
) {
1597 /* Convert to ziplist when in limits. */
1598 if (dstzset
->zsl
->length
<= server
.zset_max_ziplist_entries
&&
1599 maxelelen
<= server
.zset_max_ziplist_value
)
1600 zsetConvert(dstobj
,REDIS_ENCODING_ZIPLIST
);
1602 dbAdd(c
->db
,dstkey
,dstobj
);
1603 addReplyLongLong(c
,zsetLength(dstobj
));
1604 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1607 decrRefCount(dstobj
);
1608 addReply(c
,shared
.czero
);
1613 void zunionstoreCommand(redisClient
*c
) {
1614 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1617 void zinterstoreCommand(redisClient
*c
) {
1618 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1621 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1622 robj
*key
= c
->argv
[1];
1630 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1631 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1633 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1635 } else if (c
->argc
>= 5) {
1636 addReply(c
,shared
.syntaxerr
);
1640 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1641 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1643 /* Sanitize indexes. */
1644 llen
= zsetLength(zobj
);
1645 if (start
< 0) start
= llen
+start
;
1646 if (end
< 0) end
= llen
+end
;
1647 if (start
< 0) start
= 0;
1649 /* Invariant: start >= 0, so this test will be true when end < 0.
1650 * The range is empty when start > end or start >= length. */
1651 if (start
> end
|| start
>= llen
) {
1652 addReply(c
,shared
.emptymultibulk
);
1655 if (end
>= llen
) end
= llen
-1;
1656 rangelen
= (end
-start
)+1;
1658 /* Return the result in form of a multi-bulk reply */
1659 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1661 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1662 unsigned char *zl
= zobj
->ptr
;
1663 unsigned char *eptr
, *sptr
;
1664 unsigned char *vstr
;
1669 eptr
= ziplistIndex(zl
,-2-(2*start
));
1671 eptr
= ziplistIndex(zl
,2*start
);
1673 redisAssert(eptr
!= NULL
);
1674 sptr
= ziplistNext(zl
,eptr
);
1676 while (rangelen
--) {
1677 redisAssert(eptr
!= NULL
&& sptr
!= NULL
);
1678 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1680 addReplyBulkLongLong(c
,vlong
);
1682 addReplyBulkCBuffer(c
,vstr
,vlen
);
1685 addReplyDouble(c
,zzlGetScore(sptr
));
1688 zzlPrev(zl
,&eptr
,&sptr
);
1690 zzlNext(zl
,&eptr
,&sptr
);
1693 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1694 zset
*zs
= zobj
->ptr
;
1695 zskiplist
*zsl
= zs
->zsl
;
1699 /* Check if starting point is trivial, before doing log(N) lookup. */
1703 ln
= zslGetElementByRank(zsl
,llen
-start
);
1705 ln
= zsl
->header
->level
[0].forward
;
1707 ln
= zslGetElementByRank(zsl
,start
+1);
1711 redisAssert(ln
!= NULL
);
1713 addReplyBulk(c
,ele
);
1715 addReplyDouble(c
,ln
->score
);
1716 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1719 redisPanic("Unknown sorted set encoding");
1723 void zrangeCommand(redisClient
*c
) {
1724 zrangeGenericCommand(c
,0);
1727 void zrevrangeCommand(redisClient
*c
) {
1728 zrangeGenericCommand(c
,1);
1731 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1732 * If "justcount", only the number of elements in the range is returned. */
1733 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1735 robj
*key
= c
->argv
[1];
1736 robj
*emptyreply
, *zobj
;
1737 int offset
= 0, limit
= -1;
1739 unsigned long rangelen
= 0;
1740 void *replylen
= NULL
;
1743 /* Parse the range arguments. */
1745 /* Range is given as [max,min] */
1746 maxidx
= 2; minidx
= 3;
1748 /* Range is given as [min,max] */
1749 minidx
= 2; maxidx
= 3;
1752 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1753 addReplyError(c
,"min or max is not a double");
1757 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1758 * 4 arguments, so we'll never enter the following code path. */
1760 int remaining
= c
->argc
- 4;
1764 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1767 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1768 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1769 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1770 pos
+= 3; remaining
-= 3;
1772 addReply(c
,shared
.syntaxerr
);
1778 /* Ok, lookup the key and get the range */
1779 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1780 if ((zobj
= lookupKeyReadOrReply(c
,key
,emptyreply
)) == NULL
||
1781 checkType(c
,zobj
,REDIS_ZSET
)) return;
1783 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1784 unsigned char *zl
= zobj
->ptr
;
1785 unsigned char *eptr
, *sptr
;
1786 unsigned char *vstr
;
1791 /* If reversed, get the last node in range as starting point. */
1793 eptr
= zzlLastInRange(zl
,range
);
1795 eptr
= zzlFirstInRange(zl
,range
);
1797 /* No "first" element in the specified interval. */
1799 addReply(c
,emptyreply
);
1803 /* Get score pointer for the first element. */
1804 redisAssert(eptr
!= NULL
);
1805 sptr
= ziplistNext(zl
,eptr
);
1807 /* We don't know in advance how many matching elements there are in the
1808 * list, so we push this object that will represent the multi-bulk
1809 * length in the output buffer, and will "fix" it later */
1811 replylen
= addDeferredMultiBulkLength(c
);
1813 /* If there is an offset, just traverse the number of elements without
1814 * checking the score because that is done in the next loop. */
1815 while (eptr
&& offset
--)
1817 zzlPrev(zl
,&eptr
,&sptr
);
1819 zzlNext(zl
,&eptr
,&sptr
);
1821 while (eptr
&& limit
--) {
1822 score
= zzlGetScore(sptr
);
1824 /* Abort when the node is no longer in range. */
1826 if (!zslValueGteMin(score
,&range
)) break;
1828 if (!zslValueLteMax(score
,&range
)) break;
1834 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1836 addReplyBulkLongLong(c
,vlong
);
1838 addReplyBulkCBuffer(c
,vstr
,vlen
);
1841 addReplyDouble(c
,score
);
1844 /* Move to next node */
1846 zzlPrev(zl
,&eptr
,&sptr
);
1848 zzlNext(zl
,&eptr
,&sptr
);
1850 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1851 zset
*zs
= zobj
->ptr
;
1852 zskiplist
*zsl
= zs
->zsl
;
1855 /* If reversed, get the last node in range as starting point. */
1857 ln
= zslLastInRange(zsl
,range
);
1859 ln
= zslFirstInRange(zsl
,range
);
1861 /* No "first" element in the specified interval. */
1863 addReply(c
,emptyreply
);
1867 /* We don't know in advance how many matching elements there are in the
1868 * list, so we push this object that will represent the multi-bulk
1869 * length in the output buffer, and will "fix" it later */
1871 replylen
= addDeferredMultiBulkLength(c
);
1873 /* If there is an offset, just traverse the number of elements without
1874 * checking the score because that is done in the next loop. */
1875 while (ln
&& offset
--)
1876 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1878 while (ln
&& limit
--) {
1879 /* Abort when the node is no longer in range. */
1881 if (!zslValueGteMin(ln
->score
,&range
)) break;
1883 if (!zslValueLteMax(ln
->score
,&range
)) break;
1889 addReplyBulk(c
,ln
->obj
);
1891 addReplyDouble(c
,ln
->score
);
1894 /* Move to next node */
1895 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1898 redisPanic("Unknown sorted set encoding");
1902 addReplyLongLong(c
,(long)rangelen
);
1904 if (withscores
) rangelen
*= 2;
1905 setDeferredMultiBulkLength(c
,replylen
,rangelen
);
1909 void zrangebyscoreCommand(redisClient
*c
) {
1910 genericZrangebyscoreCommand(c
,0,0);
1913 void zrevrangebyscoreCommand(redisClient
*c
) {
1914 genericZrangebyscoreCommand(c
,1,0);
1917 void zcountCommand(redisClient
*c
) {
1918 genericZrangebyscoreCommand(c
,0,1);
1921 void zcardCommand(redisClient
*c
) {
1922 robj
*key
= c
->argv
[1];
1925 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
1926 checkType(c
,zobj
,REDIS_ZSET
)) return;
1928 addReplyLongLong(c
,zsetLength(zobj
));
1931 void zscoreCommand(redisClient
*c
) {
1932 robj
*key
= c
->argv
[1];
1936 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1937 checkType(c
,zobj
,REDIS_ZSET
)) return;
1939 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1940 if (zzlFind(zobj
->ptr
,c
->argv
[2],&score
) != NULL
)
1941 addReplyDouble(c
,score
);
1943 addReply(c
,shared
.nullbulk
);
1944 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1945 zset
*zs
= zobj
->ptr
;
1948 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1949 de
= dictFind(zs
->dict
,c
->argv
[2]);
1951 score
= *(double*)dictGetEntryVal(de
);
1952 addReplyDouble(c
,score
);
1954 addReply(c
,shared
.nullbulk
);
1957 redisPanic("Unknown sorted set encoding");
1961 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1962 robj
*key
= c
->argv
[1];
1963 robj
*ele
= c
->argv
[2];
1968 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1969 checkType(c
,zobj
,REDIS_ZSET
)) return;
1970 llen
= zsetLength(zobj
);
1972 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
1973 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1974 unsigned char *zl
= zobj
->ptr
;
1975 unsigned char *eptr
, *sptr
;
1977 eptr
= ziplistIndex(zl
,0);
1978 redisAssert(eptr
!= NULL
);
1979 sptr
= ziplistNext(zl
,eptr
);
1980 redisAssert(sptr
!= NULL
);
1983 while(eptr
!= NULL
) {
1984 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
1987 zzlNext(zl
,&eptr
,&sptr
);
1992 addReplyLongLong(c
,llen
-rank
);
1994 addReplyLongLong(c
,rank
-1);
1996 addReply(c
,shared
.nullbulk
);
1998 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1999 zset
*zs
= zobj
->ptr
;
2000 zskiplist
*zsl
= zs
->zsl
;
2004 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2005 de
= dictFind(zs
->dict
,ele
);
2007 score
= *(double*)dictGetEntryVal(de
);
2008 rank
= zslGetRank(zsl
,score
,ele
);
2009 redisAssert(rank
); /* Existing elements always have a rank. */
2011 addReplyLongLong(c
,llen
-rank
);
2013 addReplyLongLong(c
,rank
-1);
2015 addReply(c
,shared
.nullbulk
);
2018 redisPanic("Unknown sorted set encoding");
2022 void zrankCommand(redisClient
*c
) {
2023 zrankGenericCommand(c
, 0);
2026 void zrevrankCommand(redisClient
*c
) {
2027 zrankGenericCommand(c
, 1);