]>
git.saurik.com Git - redis.git/blob - src/t_zset.c
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 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1016 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1017 zset
*zs
= zobj
->ptr
;
1018 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1019 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1020 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1022 redisPanic("Unknown sorted set encoding");
1025 if (deleted
) signalModifiedKey(c
->db
,key
);
1026 server
.dirty
+= deleted
;
1027 addReplyLongLong(c
,deleted
);
1030 void zremrangebyrankCommand(redisClient
*c
) {
1031 robj
*key
= c
->argv
[1];
1036 unsigned long deleted
;
1038 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1039 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1041 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1042 checkType(c
,zobj
,REDIS_ZSET
)) return;
1044 /* Sanitize indexes. */
1045 llen
= zsetLength(zobj
);
1046 if (start
< 0) start
= llen
+start
;
1047 if (end
< 0) end
= llen
+end
;
1048 if (start
< 0) start
= 0;
1050 /* Invariant: start >= 0, so this test will be true when end < 0.
1051 * The range is empty when start > end or start >= length. */
1052 if (start
> end
|| start
>= llen
) {
1053 addReply(c
,shared
.czero
);
1056 if (end
>= llen
) end
= llen
-1;
1058 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1059 /* Correct for 1-based rank. */
1060 zobj
->ptr
= zzlDeleteRangeByRank(zobj
->ptr
,start
+1,end
+1,&deleted
);
1061 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1062 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1063 zset
*zs
= zobj
->ptr
;
1065 /* Correct for 1-based rank. */
1066 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1067 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1068 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1070 redisPanic("Unknown sorted set encoding");
1073 if (deleted
) signalModifiedKey(c
->db
,key
);
1074 server
.dirty
+= deleted
;
1075 addReplyLongLong(c
,deleted
);
1080 int type
; /* Set, sorted set */
1085 /* Set iterators. */
1098 /* Sorted set iterators. */
1102 unsigned char *eptr
, *sptr
;
1106 zskiplistNode
*node
;
1113 /* Use dirty flags for pointers that need to be cleaned up in the next
1114 * iteration over the zsetopval. The dirty flag for the long long value is
1115 * special, since long long values don't need cleanup. Instead, it means that
1116 * we already checked that "ell" holds a long long, or tried to convert another
1117 * representation into a long long value. When this was successful,
1118 * OPVAL_VALID_LL is set as well. */
1119 #define OPVAL_DIRTY_ROBJ 1
1120 #define OPVAL_DIRTY_LL 2
1121 #define OPVAL_VALID_LL 4
1123 /* Store value retrieved from the iterator. */
1126 unsigned char _buf
[32]; /* Private buffer. */
1128 unsigned char *estr
;
1134 typedef union _iterset iterset
;
1135 typedef union _iterzset iterzset
;
1137 void zuiInitIterator(zsetopsrc
*op
) {
1138 if (op
->subject
== NULL
)
1141 if (op
->type
== REDIS_SET
) {
1142 iterset
*it
= &op
->iter
.set
;
1143 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1144 it
->is
.is
= op
->subject
->ptr
;
1146 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1147 it
->ht
.dict
= op
->subject
->ptr
;
1148 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1149 it
->ht
.de
= dictNext(it
->ht
.di
);
1151 redisPanic("Unknown set encoding");
1153 } else if (op
->type
== REDIS_ZSET
) {
1154 iterzset
*it
= &op
->iter
.zset
;
1155 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1156 it
->zl
.zl
= op
->subject
->ptr
;
1157 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1158 if (it
->zl
.eptr
!= NULL
) {
1159 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1160 redisAssert(it
->zl
.sptr
!= NULL
);
1162 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1163 it
->sl
.zs
= op
->subject
->ptr
;
1164 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1166 redisPanic("Unknown sorted set encoding");
1169 redisPanic("Unsupported type");
1173 void zuiClearIterator(zsetopsrc
*op
) {
1174 if (op
->subject
== NULL
)
1177 if (op
->type
== REDIS_SET
) {
1178 iterset
*it
= &op
->iter
.set
;
1179 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1180 REDIS_NOTUSED(it
); /* skip */
1181 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1182 dictReleaseIterator(it
->ht
.di
);
1184 redisPanic("Unknown set encoding");
1186 } else if (op
->type
== REDIS_ZSET
) {
1187 iterzset
*it
= &op
->iter
.zset
;
1188 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1189 REDIS_NOTUSED(it
); /* skip */
1190 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1191 REDIS_NOTUSED(it
); /* skip */
1193 redisPanic("Unknown sorted set encoding");
1196 redisPanic("Unsupported type");
1200 int zuiLength(zsetopsrc
*op
) {
1201 if (op
->subject
== NULL
)
1204 if (op
->type
== REDIS_SET
) {
1205 iterset
*it
= &op
->iter
.set
;
1206 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1207 return intsetLen(it
->is
.is
);
1208 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1209 return dictSize(it
->ht
.dict
);
1211 redisPanic("Unknown set encoding");
1213 } else if (op
->type
== REDIS_ZSET
) {
1214 iterzset
*it
= &op
->iter
.zset
;
1215 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1216 return zzlLength(it
->zl
.zl
);
1217 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1218 return it
->sl
.zs
->zsl
->length
;
1220 redisPanic("Unknown sorted set encoding");
1223 redisPanic("Unsupported type");
1227 /* Check if the current value is valid. If so, store it in the passed structure
1228 * and move to the next element. If not valid, this means we have reached the
1229 * end of the structure and can abort. */
1230 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1231 if (op
->subject
== NULL
)
1234 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1235 decrRefCount(val
->ele
);
1237 bzero(val
,sizeof(zsetopval
));
1239 if (op
->type
== REDIS_SET
) {
1240 iterset
*it
= &op
->iter
.set
;
1241 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1242 if (!intsetGet(it
->is
.is
,it
->is
.ii
,&val
->ell
))
1246 /* Move to next element. */
1248 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1249 if (it
->ht
.de
== NULL
)
1251 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1254 /* Move to next element. */
1255 it
->ht
.de
= dictNext(it
->ht
.di
);
1257 redisPanic("Unknown set encoding");
1259 } else if (op
->type
== REDIS_ZSET
) {
1260 iterzset
*it
= &op
->iter
.zset
;
1261 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1262 /* No need to check both, but better be explicit. */
1263 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1265 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1266 val
->score
= zzlGetScore(it
->zl
.sptr
);
1268 /* Move to next element. */
1269 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1270 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1271 if (it
->sl
.node
== NULL
)
1273 val
->ele
= it
->sl
.node
->obj
;
1274 val
->score
= it
->sl
.node
->score
;
1276 /* Move to next element. */
1277 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1279 redisPanic("Unknown sorted set encoding");
1282 redisPanic("Unsupported type");
1287 int zuiLongLongFromValue(zsetopval
*val
) {
1288 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1289 val
->flags
|= OPVAL_DIRTY_LL
;
1291 if (val
->ele
!= NULL
) {
1292 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1293 val
->ell
= (long)val
->ele
->ptr
;
1294 val
->flags
|= OPVAL_VALID_LL
;
1295 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1296 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1297 val
->flags
|= OPVAL_VALID_LL
;
1299 redisPanic("Unsupported element encoding");
1301 } else if (val
->estr
!= NULL
) {
1302 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1303 val
->flags
|= OPVAL_VALID_LL
;
1305 /* The long long was already set, flag as valid. */
1306 val
->flags
|= OPVAL_VALID_LL
;
1309 return val
->flags
& OPVAL_VALID_LL
;
1312 robj
*zuiObjectFromValue(zsetopval
*val
) {
1313 if (val
->ele
== NULL
) {
1314 if (val
->estr
!= NULL
) {
1315 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1317 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1319 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1324 int zuiBufferFromValue(zsetopval
*val
) {
1325 if (val
->estr
== NULL
) {
1326 if (val
->ele
!= NULL
) {
1327 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1328 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1329 val
->estr
= val
->_buf
;
1330 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1331 val
->elen
= sdslen(val
->ele
->ptr
);
1332 val
->estr
= val
->ele
->ptr
;
1334 redisPanic("Unsupported element encoding");
1337 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1338 val
->estr
= val
->_buf
;
1344 /* Find value pointed to by val in the source pointer to by op. When found,
1345 * return 1 and store its score in target. Return 0 otherwise. */
1346 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1347 if (op
->subject
== NULL
)
1350 if (op
->type
== REDIS_SET
) {
1351 iterset
*it
= &op
->iter
.set
;
1353 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1354 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1360 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1361 zuiObjectFromValue(val
);
1362 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1369 redisPanic("Unknown set encoding");
1371 } else if (op
->type
== REDIS_ZSET
) {
1372 iterzset
*it
= &op
->iter
.zset
;
1373 zuiObjectFromValue(val
);
1375 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1376 if (zzlFind(it
->zl
.zl
,val
->ele
,score
) != NULL
) {
1377 /* Score is already set by zzlFind. */
1382 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1384 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1385 *score
= *(double*)dictGetEntryVal(de
);
1391 redisPanic("Unknown sorted set encoding");
1394 redisPanic("Unsupported type");
1398 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1399 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1402 #define REDIS_AGGR_SUM 1
1403 #define REDIS_AGGR_MIN 2
1404 #define REDIS_AGGR_MAX 3
1405 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1407 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1408 if (aggregate
== REDIS_AGGR_SUM
) {
1409 *target
= *target
+ val
;
1410 /* The result of adding two doubles is NaN when one variable
1411 * is +inf and the other is -inf. When these numbers are added,
1412 * we maintain the convention of the result being 0.0. */
1413 if (isnan(*target
)) *target
= 0.0;
1414 } else if (aggregate
== REDIS_AGGR_MIN
) {
1415 *target
= val
< *target
? val
: *target
;
1416 } else if (aggregate
== REDIS_AGGR_MAX
) {
1417 *target
= val
> *target
? val
: *target
;
1420 redisPanic("Unknown ZUNION/INTER aggregate type");
1424 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1426 int aggregate
= REDIS_AGGR_SUM
;
1430 unsigned int maxelelen
= 0;
1433 zskiplistNode
*znode
;
1436 /* expect setnum input keys to be given */
1437 setnum
= atoi(c
->argv
[2]->ptr
);
1440 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1444 /* test if the expected number of keys would overflow */
1445 if (3+setnum
> c
->argc
) {
1446 addReply(c
,shared
.syntaxerr
);
1450 /* read keys to be used for input */
1451 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1452 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1453 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1455 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1457 addReply(c
,shared
.wrongtypeerr
);
1461 src
[i
].subject
= obj
;
1462 src
[i
].type
= obj
->type
;
1463 src
[i
].encoding
= obj
->encoding
;
1465 src
[i
].subject
= NULL
;
1468 /* Default all weights to 1. */
1469 src
[i
].weight
= 1.0;
1472 /* parse optional extra arguments */
1474 int remaining
= c
->argc
- j
;
1477 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1479 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1480 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1481 "weight value is not a double") != REDIS_OK
)
1487 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1489 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1490 aggregate
= REDIS_AGGR_SUM
;
1491 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1492 aggregate
= REDIS_AGGR_MIN
;
1493 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1494 aggregate
= REDIS_AGGR_MAX
;
1497 addReply(c
,shared
.syntaxerr
);
1503 addReply(c
,shared
.syntaxerr
);
1509 for (i
= 0; i
< setnum
; i
++)
1510 zuiInitIterator(&src
[i
]);
1512 /* sort sets from the smallest to largest, this will improve our
1513 * algorithm's performance */
1514 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1516 dstobj
= createZsetObject();
1517 dstzset
= dstobj
->ptr
;
1519 if (op
== REDIS_OP_INTER
) {
1520 /* Skip everything if the smallest input is empty. */
1521 if (zuiLength(&src
[0]) > 0) {
1522 /* Precondition: as src[0] is non-empty and the inputs are ordered
1523 * by size, all src[i > 0] are non-empty too. */
1524 while (zuiNext(&src
[0],&zval
)) {
1525 double score
, value
;
1527 score
= src
[0].weight
* zval
.score
;
1528 for (j
= 1; j
< setnum
; j
++) {
1529 if (zuiFind(&src
[j
],&zval
,&value
)) {
1530 value
*= src
[j
].weight
;
1531 zunionInterAggregate(&score
,value
,aggregate
);
1537 /* Only continue when present in every input. */
1539 tmp
= zuiObjectFromValue(&zval
);
1540 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1541 incrRefCount(tmp
); /* added to skiplist */
1542 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1543 incrRefCount(tmp
); /* added to dictionary */
1545 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1546 if (sdslen(tmp
->ptr
) > maxelelen
)
1547 maxelelen
= sdslen(tmp
->ptr
);
1551 } else if (op
== REDIS_OP_UNION
) {
1552 for (i
= 0; i
< setnum
; i
++) {
1553 if (zuiLength(&src
[0]) == 0)
1556 while (zuiNext(&src
[i
],&zval
)) {
1557 double score
, value
;
1559 /* Skip key when already processed */
1560 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1563 /* Initialize score */
1564 score
= src
[i
].weight
* zval
.score
;
1566 /* Because the inputs are sorted by size, it's only possible
1567 * for sets at larger indices to hold this element. */
1568 for (j
= (i
+1); j
< setnum
; j
++) {
1569 if (zuiFind(&src
[j
],&zval
,&value
)) {
1570 value
*= src
[j
].weight
;
1571 zunionInterAggregate(&score
,value
,aggregate
);
1575 tmp
= zuiObjectFromValue(&zval
);
1576 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1577 incrRefCount(zval
.ele
); /* added to skiplist */
1578 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1579 incrRefCount(zval
.ele
); /* added to dictionary */
1581 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1582 if (sdslen(tmp
->ptr
) > maxelelen
)
1583 maxelelen
= sdslen(tmp
->ptr
);
1587 redisPanic("Unknown operator");
1590 for (i
= 0; i
< setnum
; i
++)
1591 zuiClearIterator(&src
[i
]);
1593 if (dbDelete(c
->db
,dstkey
)) {
1594 signalModifiedKey(c
->db
,dstkey
);
1598 if (dstzset
->zsl
->length
) {
1599 /* Convert to ziplist when in limits. */
1600 if (dstzset
->zsl
->length
<= server
.zset_max_ziplist_entries
&&
1601 maxelelen
<= server
.zset_max_ziplist_value
)
1602 zsetConvert(dstobj
,REDIS_ENCODING_ZIPLIST
);
1604 dbAdd(c
->db
,dstkey
,dstobj
);
1605 addReplyLongLong(c
,zsetLength(dstobj
));
1606 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1609 decrRefCount(dstobj
);
1610 addReply(c
,shared
.czero
);
1615 void zunionstoreCommand(redisClient
*c
) {
1616 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1619 void zinterstoreCommand(redisClient
*c
) {
1620 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1623 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1624 robj
*key
= c
->argv
[1];
1632 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1633 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1635 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1637 } else if (c
->argc
>= 5) {
1638 addReply(c
,shared
.syntaxerr
);
1642 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1643 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1645 /* Sanitize indexes. */
1646 llen
= zsetLength(zobj
);
1647 if (start
< 0) start
= llen
+start
;
1648 if (end
< 0) end
= llen
+end
;
1649 if (start
< 0) start
= 0;
1651 /* Invariant: start >= 0, so this test will be true when end < 0.
1652 * The range is empty when start > end or start >= length. */
1653 if (start
> end
|| start
>= llen
) {
1654 addReply(c
,shared
.emptymultibulk
);
1657 if (end
>= llen
) end
= llen
-1;
1658 rangelen
= (end
-start
)+1;
1660 /* Return the result in form of a multi-bulk reply */
1661 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1663 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1664 unsigned char *zl
= zobj
->ptr
;
1665 unsigned char *eptr
, *sptr
;
1666 unsigned char *vstr
;
1671 eptr
= ziplistIndex(zl
,-2-(2*start
));
1673 eptr
= ziplistIndex(zl
,2*start
);
1675 redisAssert(eptr
!= NULL
);
1676 sptr
= ziplistNext(zl
,eptr
);
1678 while (rangelen
--) {
1679 redisAssert(eptr
!= NULL
&& sptr
!= NULL
);
1680 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1682 addReplyBulkLongLong(c
,vlong
);
1684 addReplyBulkCBuffer(c
,vstr
,vlen
);
1687 addReplyDouble(c
,zzlGetScore(sptr
));
1690 zzlPrev(zl
,&eptr
,&sptr
);
1692 zzlNext(zl
,&eptr
,&sptr
);
1695 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1696 zset
*zs
= zobj
->ptr
;
1697 zskiplist
*zsl
= zs
->zsl
;
1701 /* Check if starting point is trivial, before doing log(N) lookup. */
1705 ln
= zslGetElementByRank(zsl
,llen
-start
);
1707 ln
= zsl
->header
->level
[0].forward
;
1709 ln
= zslGetElementByRank(zsl
,start
+1);
1713 redisAssert(ln
!= NULL
);
1715 addReplyBulk(c
,ele
);
1717 addReplyDouble(c
,ln
->score
);
1718 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1721 redisPanic("Unknown sorted set encoding");
1725 void zrangeCommand(redisClient
*c
) {
1726 zrangeGenericCommand(c
,0);
1729 void zrevrangeCommand(redisClient
*c
) {
1730 zrangeGenericCommand(c
,1);
1733 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1734 * If "justcount", only the number of elements in the range is returned. */
1735 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1737 robj
*key
= c
->argv
[1];
1738 robj
*emptyreply
, *zobj
;
1739 int offset
= 0, limit
= -1;
1741 unsigned long rangelen
= 0;
1742 void *replylen
= NULL
;
1745 /* Parse the range arguments. */
1747 /* Range is given as [max,min] */
1748 maxidx
= 2; minidx
= 3;
1750 /* Range is given as [min,max] */
1751 minidx
= 2; maxidx
= 3;
1754 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1755 addReplyError(c
,"min or max is not a double");
1759 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1760 * 4 arguments, so we'll never enter the following code path. */
1762 int remaining
= c
->argc
- 4;
1766 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1769 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1770 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1771 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1772 pos
+= 3; remaining
-= 3;
1774 addReply(c
,shared
.syntaxerr
);
1780 /* Ok, lookup the key and get the range */
1781 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1782 if ((zobj
= lookupKeyReadOrReply(c
,key
,emptyreply
)) == NULL
||
1783 checkType(c
,zobj
,REDIS_ZSET
)) return;
1785 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1786 unsigned char *zl
= zobj
->ptr
;
1787 unsigned char *eptr
, *sptr
;
1788 unsigned char *vstr
;
1793 /* If reversed, get the last node in range as starting point. */
1795 eptr
= zzlLastInRange(zl
,range
);
1797 eptr
= zzlFirstInRange(zl
,range
);
1799 /* No "first" element in the specified interval. */
1801 addReply(c
,emptyreply
);
1805 /* Get score pointer for the first element. */
1806 redisAssert(eptr
!= NULL
);
1807 sptr
= ziplistNext(zl
,eptr
);
1809 /* We don't know in advance how many matching elements there are in the
1810 * list, so we push this object that will represent the multi-bulk
1811 * length in the output buffer, and will "fix" it later */
1813 replylen
= addDeferredMultiBulkLength(c
);
1815 /* If there is an offset, just traverse the number of elements without
1816 * checking the score because that is done in the next loop. */
1817 while (eptr
&& offset
--)
1819 zzlPrev(zl
,&eptr
,&sptr
);
1821 zzlNext(zl
,&eptr
,&sptr
);
1823 while (eptr
&& limit
--) {
1824 score
= zzlGetScore(sptr
);
1826 /* Abort when the node is no longer in range. */
1828 if (!zslValueGteMin(score
,&range
)) break;
1830 if (!zslValueLteMax(score
,&range
)) break;
1836 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1838 addReplyBulkLongLong(c
,vlong
);
1840 addReplyBulkCBuffer(c
,vstr
,vlen
);
1843 addReplyDouble(c
,score
);
1846 /* Move to next node */
1848 zzlPrev(zl
,&eptr
,&sptr
);
1850 zzlNext(zl
,&eptr
,&sptr
);
1852 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1853 zset
*zs
= zobj
->ptr
;
1854 zskiplist
*zsl
= zs
->zsl
;
1857 /* If reversed, get the last node in range as starting point. */
1859 ln
= zslLastInRange(zsl
,range
);
1861 ln
= zslFirstInRange(zsl
,range
);
1863 /* No "first" element in the specified interval. */
1865 addReply(c
,emptyreply
);
1869 /* We don't know in advance how many matching elements there are in the
1870 * list, so we push this object that will represent the multi-bulk
1871 * length in the output buffer, and will "fix" it later */
1873 replylen
= addDeferredMultiBulkLength(c
);
1875 /* If there is an offset, just traverse the number of elements without
1876 * checking the score because that is done in the next loop. */
1877 while (ln
&& offset
--)
1878 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1880 while (ln
&& limit
--) {
1881 /* Abort when the node is no longer in range. */
1883 if (!zslValueGteMin(ln
->score
,&range
)) break;
1885 if (!zslValueLteMax(ln
->score
,&range
)) break;
1891 addReplyBulk(c
,ln
->obj
);
1893 addReplyDouble(c
,ln
->score
);
1896 /* Move to next node */
1897 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1900 redisPanic("Unknown sorted set encoding");
1904 addReplyLongLong(c
,(long)rangelen
);
1906 if (withscores
) rangelen
*= 2;
1907 setDeferredMultiBulkLength(c
,replylen
,rangelen
);
1911 void zrangebyscoreCommand(redisClient
*c
) {
1912 genericZrangebyscoreCommand(c
,0,0);
1915 void zrevrangebyscoreCommand(redisClient
*c
) {
1916 genericZrangebyscoreCommand(c
,1,0);
1919 void zcountCommand(redisClient
*c
) {
1920 genericZrangebyscoreCommand(c
,0,1);
1923 void zcardCommand(redisClient
*c
) {
1924 robj
*key
= c
->argv
[1];
1927 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
1928 checkType(c
,zobj
,REDIS_ZSET
)) return;
1930 addReplyLongLong(c
,zsetLength(zobj
));
1933 void zscoreCommand(redisClient
*c
) {
1934 robj
*key
= c
->argv
[1];
1938 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1939 checkType(c
,zobj
,REDIS_ZSET
)) return;
1941 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1942 if (zzlFind(zobj
->ptr
,c
->argv
[2],&score
) != NULL
)
1943 addReplyDouble(c
,score
);
1945 addReply(c
,shared
.nullbulk
);
1946 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1947 zset
*zs
= zobj
->ptr
;
1950 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1951 de
= dictFind(zs
->dict
,c
->argv
[2]);
1953 score
= *(double*)dictGetEntryVal(de
);
1954 addReplyDouble(c
,score
);
1956 addReply(c
,shared
.nullbulk
);
1959 redisPanic("Unknown sorted set encoding");
1963 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1964 robj
*key
= c
->argv
[1];
1965 robj
*ele
= c
->argv
[2];
1970 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1971 checkType(c
,zobj
,REDIS_ZSET
)) return;
1972 llen
= zsetLength(zobj
);
1974 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
1975 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1976 unsigned char *zl
= zobj
->ptr
;
1977 unsigned char *eptr
, *sptr
;
1979 eptr
= ziplistIndex(zl
,0);
1980 redisAssert(eptr
!= NULL
);
1981 sptr
= ziplistNext(zl
,eptr
);
1982 redisAssert(sptr
!= NULL
);
1985 while(eptr
!= NULL
) {
1986 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
1989 zzlNext(zl
,&eptr
,&sptr
);
1994 addReplyLongLong(c
,llen
-rank
);
1996 addReplyLongLong(c
,rank
-1);
1998 addReply(c
,shared
.nullbulk
);
2000 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
2001 zset
*zs
= zobj
->ptr
;
2002 zskiplist
*zsl
= zs
->zsl
;
2006 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2007 de
= dictFind(zs
->dict
,ele
);
2009 score
= *(double*)dictGetEntryVal(de
);
2010 rank
= zslGetRank(zsl
,score
,ele
);
2011 redisAssert(rank
); /* Existing elements always have a rank. */
2013 addReplyLongLong(c
,llen
-rank
);
2015 addReplyLongLong(c
,rank
-1);
2017 addReply(c
,shared
.nullbulk
);
2020 redisPanic("Unknown sorted set encoding");
2024 void zrankCommand(redisClient
*c
) {
2025 zrankGenericCommand(c
, 0);
2028 void zrevrankCommand(redisClient
*c
) {
2029 zrankGenericCommand(c
, 1);