]>
git.saurik.com Git - redis.git/blob - src/t_zset.c
b8a961eb775022e46ef2468ecbb54334a6ce6520
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 static int zslValueInRange(double value
, zrangespec
*spec
) {
192 return zslValueGteMin(value
,spec
) && zslValueLteMax(value
,spec
);
195 /* Returns if there is a part of the zset is in range. */
196 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
199 /* Test for ranges that will always be empty. */
200 if (range
->min
> range
->max
||
201 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
204 if (x
== NULL
|| !zslValueGteMin(x
->score
,range
))
206 x
= zsl
->header
->level
[0].forward
;
207 if (x
== NULL
|| !zslValueLteMax(x
->score
,range
))
212 /* Find the first node that is contained in the specified range.
213 * Returns NULL when no element is contained in the range. */
214 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
218 /* If everything is out of range, return early. */
219 if (!zslIsInRange(zsl
,&range
)) return NULL
;
222 for (i
= zsl
->level
-1; i
>= 0; i
--) {
223 /* Go forward while *OUT* of range. */
224 while (x
->level
[i
].forward
&&
225 !zslValueGteMin(x
->level
[i
].forward
->score
,&range
))
226 x
= x
->level
[i
].forward
;
229 /* This is an inner range, so the next node cannot be NULL. */
230 x
= x
->level
[0].forward
;
231 redisAssert(x
!= NULL
);
233 /* Check if score <= max. */
234 if (!zslValueLteMax(x
->score
,&range
)) return NULL
;
238 /* Find the last node that is contained in the specified range.
239 * Returns NULL when no element is contained in the range. */
240 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
244 /* If everything is out of range, return early. */
245 if (!zslIsInRange(zsl
,&range
)) return NULL
;
248 for (i
= zsl
->level
-1; i
>= 0; i
--) {
249 /* Go forward while *IN* range. */
250 while (x
->level
[i
].forward
&&
251 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
252 x
= x
->level
[i
].forward
;
255 /* This is an inner range, so this node cannot be NULL. */
256 redisAssert(x
!= NULL
);
258 /* Check if score >= min. */
259 if (!zslValueGteMin(x
->score
,&range
)) return NULL
;
263 /* Delete all the elements with score between min and max from the skiplist.
264 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
265 * Note that this function takes the reference to the hash table view of the
266 * sorted set, in order to remove the elements from the hash table too. */
267 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
268 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
269 unsigned long removed
= 0;
273 for (i
= zsl
->level
-1; i
>= 0; i
--) {
274 while (x
->level
[i
].forward
&& (range
.minex
?
275 x
->level
[i
].forward
->score
<= range
.min
:
276 x
->level
[i
].forward
->score
< range
.min
))
277 x
= x
->level
[i
].forward
;
281 /* Current node is the last with score < or <= min. */
282 x
= x
->level
[0].forward
;
284 /* Delete nodes while in range. */
285 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
286 zskiplistNode
*next
= x
->level
[0].forward
;
287 zslDeleteNode(zsl
,x
,update
);
288 dictDelete(dict
,x
->obj
);
296 /* Delete all the elements with rank between start and end from the skiplist.
297 * Start and end are inclusive. Note that start and end need to be 1-based */
298 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
299 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
300 unsigned long traversed
= 0, removed
= 0;
304 for (i
= zsl
->level
-1; i
>= 0; i
--) {
305 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
306 traversed
+= x
->level
[i
].span
;
307 x
= x
->level
[i
].forward
;
313 x
= x
->level
[0].forward
;
314 while (x
&& traversed
<= end
) {
315 zskiplistNode
*next
= x
->level
[0].forward
;
316 zslDeleteNode(zsl
,x
,update
);
317 dictDelete(dict
,x
->obj
);
326 /* Find the rank for an element by both score and key.
327 * Returns 0 when the element cannot be found, rank otherwise.
328 * Note that the rank is 1-based due to the span of zsl->header to the
330 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
332 unsigned long rank
= 0;
336 for (i
= zsl
->level
-1; i
>= 0; i
--) {
337 while (x
->level
[i
].forward
&&
338 (x
->level
[i
].forward
->score
< score
||
339 (x
->level
[i
].forward
->score
== score
&&
340 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
341 rank
+= x
->level
[i
].span
;
342 x
= x
->level
[i
].forward
;
345 /* x might be equal to zsl->header, so test if obj is non-NULL */
346 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
353 /* Finds an element by its rank. The rank argument needs to be 1-based. */
354 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
356 unsigned long traversed
= 0;
360 for (i
= zsl
->level
-1; i
>= 0; i
--) {
361 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
363 traversed
+= x
->level
[i
].span
;
364 x
= x
->level
[i
].forward
;
366 if (traversed
== rank
) {
373 /* Populate the rangespec according to the objects min and max. */
374 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
376 spec
->minex
= spec
->maxex
= 0;
378 /* Parse the min-max interval. If one of the values is prefixed
379 * by the "(" character, it's considered "open". For instance
380 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
381 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
382 if (min
->encoding
== REDIS_ENCODING_INT
) {
383 spec
->min
= (long)min
->ptr
;
385 if (((char*)min
->ptr
)[0] == '(') {
386 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
387 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
390 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
391 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
394 if (max
->encoding
== REDIS_ENCODING_INT
) {
395 spec
->max
= (long)max
->ptr
;
397 if (((char*)max
->ptr
)[0] == '(') {
398 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
399 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
402 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
403 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
410 /*-----------------------------------------------------------------------------
411 * Ziplist-backed sorted set API
412 *----------------------------------------------------------------------------*/
414 double zzlGetScore(unsigned char *sptr
) {
421 redisAssert(sptr
!= NULL
);
422 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
425 memcpy(buf
,vstr
,vlen
);
427 score
= strtod(buf
,NULL
);
435 /* Compare element in sorted set with given element. */
436 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
440 unsigned char vbuf
[32];
443 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
445 /* Store string representation of long long in buf. */
446 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
450 minlen
= (vlen
< clen
) ? vlen
: clen
;
451 cmp
= memcmp(vstr
,cstr
,minlen
);
452 if (cmp
== 0) return vlen
-clen
;
456 unsigned int zzlLength(unsigned char *zl
) {
457 return ziplistLen(zl
)/2;
460 /* Move to next entry based on the values in eptr and sptr. Both are set to
461 * NULL when there is no next entry. */
462 void zzlNext(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
463 unsigned char *_eptr
, *_sptr
;
464 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
466 _eptr
= ziplistNext(zl
,*sptr
);
468 _sptr
= ziplistNext(zl
,_eptr
);
469 redisAssert(_sptr
!= NULL
);
479 /* Move to the previous entry based on the values in eptr and sptr. Both are
480 * set to NULL when there is no next entry. */
481 void zzlPrev(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
482 unsigned char *_eptr
, *_sptr
;
483 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
485 _sptr
= ziplistPrev(zl
,*eptr
);
487 _eptr
= ziplistPrev(zl
,_sptr
);
488 redisAssert(_eptr
!= NULL
);
490 /* No previous entry. */
498 /* Returns if there is a part of the zset is in range. Should only be used
499 * internally by zzlFirstInRange and zzlLastInRange. */
500 int zzlIsInRange(unsigned char *zl
, zrangespec
*range
) {
504 /* Test for ranges that will always be empty. */
505 if (range
->min
> range
->max
||
506 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
509 p
= ziplistIndex(zl
,-1); /* Last score. */
510 redisAssert(p
!= NULL
);
511 score
= zzlGetScore(p
);
512 if (!zslValueGteMin(score
,range
))
515 p
= ziplistIndex(zl
,1); /* First score. */
516 redisAssert(p
!= NULL
);
517 score
= zzlGetScore(p
);
518 if (!zslValueLteMax(score
,range
))
524 /* Find pointer to the first element contained in the specified range.
525 * Returns NULL when no element is contained in the range. */
526 unsigned char *zzlFirstInRange(unsigned char *zl
, zrangespec range
) {
527 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
530 /* If everything is out of range, return early. */
531 if (!zzlIsInRange(zl
,&range
)) return NULL
;
533 while (eptr
!= NULL
) {
534 sptr
= ziplistNext(zl
,eptr
);
535 redisAssert(sptr
!= NULL
);
537 score
= zzlGetScore(sptr
);
538 if (zslValueGteMin(score
,&range
)) {
539 /* Check if score <= max. */
540 if (zslValueLteMax(score
,&range
))
545 /* Move to next element. */
546 eptr
= ziplistNext(zl
,sptr
);
552 /* Find pointer to the last element contained in the specified range.
553 * Returns NULL when no element is contained in the range. */
554 unsigned char *zzlLastInRange(unsigned char *zl
, zrangespec range
) {
555 unsigned char *eptr
= ziplistIndex(zl
,-2), *sptr
;
558 /* If everything is out of range, return early. */
559 if (!zzlIsInRange(zl
,&range
)) return NULL
;
561 while (eptr
!= NULL
) {
562 sptr
= ziplistNext(zl
,eptr
);
563 redisAssert(sptr
!= NULL
);
565 score
= zzlGetScore(sptr
);
566 if (zslValueLteMax(score
,&range
)) {
567 /* Check if score >= min. */
568 if (zslValueGteMin(score
,&range
))
573 /* Move to previous element by moving to the score of previous element.
574 * When this returns NULL, we know there also is no element. */
575 sptr
= ziplistPrev(zl
,eptr
);
577 redisAssert((eptr
= ziplistPrev(zl
,sptr
)) != NULL
);
585 unsigned char *zzlFind(unsigned char *zl
, robj
*ele
, double *score
) {
586 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
588 ele
= getDecodedObject(ele
);
589 while (eptr
!= NULL
) {
590 sptr
= ziplistNext(zl
,eptr
);
591 redisAssert(sptr
!= NULL
);
593 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
594 /* Matching element, pull out score. */
595 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
600 /* Move to next element. */
601 eptr
= ziplistNext(zl
,sptr
);
608 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
609 * don't want to modify the one given as argument. */
610 unsigned char *zzlDelete(unsigned char *zl
, unsigned char *eptr
) {
611 unsigned char *p
= eptr
;
613 /* TODO: add function to ziplist API to delete N elements from offset. */
614 zl
= ziplistDelete(zl
,&p
);
615 zl
= ziplistDelete(zl
,&p
);
619 unsigned char *zzlInsertAt(unsigned char *zl
, unsigned char *eptr
, robj
*ele
, double score
) {
625 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
626 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
628 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
629 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
631 /* Keep offset relative to zl, as it might be re-allocated. */
633 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
636 /* Insert score after the element. */
637 redisAssert((sptr
= ziplistNext(zl
,eptr
)) != NULL
);
638 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
644 /* Insert (element,score) pair in ziplist. This function assumes the element is
645 * not yet present in the list. */
646 unsigned char *zzlInsert(unsigned char *zl
, robj
*ele
, double score
) {
647 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
650 ele
= getDecodedObject(ele
);
651 while (eptr
!= NULL
) {
652 sptr
= ziplistNext(zl
,eptr
);
653 redisAssert(sptr
!= NULL
);
654 s
= zzlGetScore(sptr
);
657 /* First element with score larger than score for element to be
658 * inserted. This means we should take its spot in the list to
659 * maintain ordering. */
660 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
662 } else if (s
== score
) {
663 /* Ensure lexicographical ordering for elements. */
664 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) > 0) {
665 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
670 /* Move to next element. */
671 eptr
= ziplistNext(zl
,sptr
);
674 /* Push on tail of list when it was not yet inserted. */
676 zl
= zzlInsertAt(zl
,NULL
,ele
,score
);
682 unsigned char *zzlDeleteRangeByScore(unsigned char *zl
, zrangespec range
, unsigned long *deleted
) {
683 unsigned char *eptr
, *sptr
;
685 unsigned long num
= 0;
687 if (deleted
!= NULL
) *deleted
= 0;
689 eptr
= zzlFirstInRange(zl
,range
);
690 if (eptr
== NULL
) return zl
;
692 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
693 * byte and ziplistNext will return NULL. */
694 while ((sptr
= ziplistNext(zl
,eptr
)) != NULL
) {
695 score
= zzlGetScore(sptr
);
696 if (zslValueLteMax(score
,&range
)) {
697 /* Delete both the element and the score. */
698 zl
= ziplistDelete(zl
,&eptr
);
699 zl
= ziplistDelete(zl
,&eptr
);
702 /* No longer in range. */
707 if (deleted
!= NULL
) *deleted
= num
;
711 /* Delete all the elements with rank between start and end from the skiplist.
712 * Start and end are inclusive. Note that start and end need to be 1-based */
713 unsigned char *zzlDeleteRangeByRank(unsigned char *zl
, unsigned int start
, unsigned int end
, unsigned long *deleted
) {
714 unsigned int num
= (end
-start
)+1;
715 if (deleted
) *deleted
= num
;
716 zl
= ziplistDeleteRange(zl
,2*(start
-1),2*num
);
720 /*-----------------------------------------------------------------------------
721 * Common sorted set API
722 *----------------------------------------------------------------------------*/
724 unsigned int zsetLength(robj
*zobj
) {
726 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
727 length
= zzlLength(zobj
->ptr
);
728 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
729 length
= ((zset
*)zobj
->ptr
)->zsl
->length
;
731 redisPanic("Unknown sorted set encoding");
736 void zsetConvert(robj
*zobj
, int encoding
) {
738 zskiplistNode
*node
, *next
;
742 if (zobj
->encoding
== encoding
) return;
743 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
744 unsigned char *zl
= zobj
->ptr
;
745 unsigned char *eptr
, *sptr
;
750 if (encoding
!= REDIS_ENCODING_RAW
)
751 redisPanic("Unknown target encoding");
753 zs
= zmalloc(sizeof(*zs
));
754 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
755 zs
->zsl
= zslCreate();
757 eptr
= ziplistIndex(zl
,0);
758 redisAssert(eptr
!= NULL
);
759 sptr
= ziplistNext(zl
,eptr
);
760 redisAssert(sptr
!= NULL
);
762 while (eptr
!= NULL
) {
763 score
= zzlGetScore(sptr
);
764 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
766 ele
= createStringObjectFromLongLong(vlong
);
768 ele
= createStringObject((char*)vstr
,vlen
);
770 /* Has incremented refcount since it was just created. */
771 node
= zslInsert(zs
->zsl
,score
,ele
);
772 redisAssert(dictAdd(zs
->dict
,ele
,&node
->score
) == DICT_OK
);
773 incrRefCount(ele
); /* Added to dictionary. */
774 zzlNext(zl
,&eptr
,&sptr
);
779 zobj
->encoding
= REDIS_ENCODING_RAW
;
780 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
781 unsigned char *zl
= ziplistNew();
783 if (encoding
!= REDIS_ENCODING_ZIPLIST
)
784 redisPanic("Unknown target encoding");
786 /* Approach similar to zslFree(), since we want to free the skiplist at
787 * the same time as creating the ziplist. */
789 dictRelease(zs
->dict
);
790 node
= zs
->zsl
->header
->level
[0].forward
;
791 zfree(zs
->zsl
->header
);
795 ele
= getDecodedObject(node
->obj
);
796 zl
= zzlInsertAt(zl
,NULL
,ele
,node
->score
);
799 next
= node
->level
[0].forward
;
806 zobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
808 redisPanic("Unknown sorted set encoding");
812 /*-----------------------------------------------------------------------------
813 * Sorted set commands
814 *----------------------------------------------------------------------------*/
816 /* This generic command implements both ZADD and ZINCRBY. */
817 void zaddGenericCommand(redisClient
*c
, int incr
) {
818 static char *nanerr
= "resulting score is not a number (NaN)";
819 robj
*key
= c
->argv
[1];
823 double score
, curscore
= 0.0;
825 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&score
,NULL
) != REDIS_OK
)
828 zobj
= lookupKeyWrite(c
->db
,key
);
830 if (server
.zset_max_ziplist_entries
== 0 ||
831 server
.zset_max_ziplist_value
< sdslen(c
->argv
[3]->ptr
))
833 zobj
= createZsetObject();
835 zobj
= createZsetZiplistObject();
837 dbAdd(c
->db
,key
,zobj
);
839 if (zobj
->type
!= REDIS_ZSET
) {
840 addReply(c
,shared
.wrongtypeerr
);
845 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
848 /* Prefer non-encoded element when dealing with ziplists. */
850 if ((eptr
= zzlFind(zobj
->ptr
,ele
,&curscore
)) != NULL
) {
854 addReplyError(c
,nanerr
);
855 /* Don't need to check if the sorted set is empty, because
856 * we know it has at least one element. */
861 /* Remove and re-insert when score changed. */
862 if (score
!= curscore
) {
863 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
864 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
866 signalModifiedKey(c
->db
,key
);
870 if (incr
) /* ZINCRBY */
871 addReplyDouble(c
,score
);
873 addReply(c
,shared
.czero
);
875 /* Optimize: check if the element is too large or the list becomes
876 * too long *before* executing zzlInsert. */
877 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
878 if (zzlLength(zobj
->ptr
) > server
.zset_max_ziplist_entries
)
879 zsetConvert(zobj
,REDIS_ENCODING_RAW
);
880 if (sdslen(ele
->ptr
) > server
.zset_max_ziplist_value
)
881 zsetConvert(zobj
,REDIS_ENCODING_RAW
);
883 signalModifiedKey(c
->db
,key
);
886 if (incr
) /* ZINCRBY */
887 addReplyDouble(c
,score
);
889 addReply(c
,shared
.cone
);
891 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
892 zset
*zs
= zobj
->ptr
;
893 zskiplistNode
*znode
;
896 ele
= c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
897 de
= dictFind(zs
->dict
,ele
);
899 curobj
= dictGetEntryKey(de
);
900 curscore
= *(double*)dictGetEntryVal(de
);
905 addReplyError(c
,nanerr
);
906 /* Don't need to check if the sorted set is empty, because
907 * we know it has at least one element. */
912 /* Remove and re-insert when score changed. We can safely delete
913 * the key object from the skiplist, since the dictionary still has
914 * a reference to it. */
915 if (score
!= curscore
) {
916 redisAssert(zslDelete(zs
->zsl
,curscore
,curobj
));
917 znode
= zslInsert(zs
->zsl
,score
,curobj
);
918 incrRefCount(curobj
); /* Re-inserted in skiplist. */
919 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
921 signalModifiedKey(c
->db
,key
);
925 if (incr
) /* ZINCRBY */
926 addReplyDouble(c
,score
);
928 addReply(c
,shared
.czero
);
930 znode
= zslInsert(zs
->zsl
,score
,ele
);
931 incrRefCount(ele
); /* Inserted in skiplist. */
932 redisAssert(dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
933 incrRefCount(ele
); /* Added to dictionary. */
935 signalModifiedKey(c
->db
,key
);
938 if (incr
) /* ZINCRBY */
939 addReplyDouble(c
,score
);
941 addReply(c
,shared
.cone
);
944 redisPanic("Unknown sorted set encoding");
948 void zaddCommand(redisClient
*c
) {
949 zaddGenericCommand(c
,0);
952 void zincrbyCommand(redisClient
*c
) {
953 zaddGenericCommand(c
,1);
956 void zremCommand(redisClient
*c
) {
957 robj
*key
= c
->argv
[1];
958 robj
*ele
= c
->argv
[2];
961 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
962 checkType(c
,zobj
,REDIS_ZSET
)) return;
964 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
967 if ((eptr
= zzlFind(zobj
->ptr
,ele
,NULL
)) != NULL
) {
968 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
969 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
971 addReply(c
,shared
.czero
);
974 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
975 zset
*zs
= zobj
->ptr
;
979 de
= dictFind(zs
->dict
,ele
);
981 /* Delete from the skiplist */
982 score
= *(double*)dictGetEntryVal(de
);
983 redisAssert(zslDelete(zs
->zsl
,score
,ele
));
985 /* Delete from the hash table */
986 dictDelete(zs
->dict
,ele
);
987 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
988 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
990 addReply(c
,shared
.czero
);
994 redisPanic("Unknown sorted set encoding");
997 signalModifiedKey(c
->db
,key
);
999 addReply(c
,shared
.cone
);
1002 void zremrangebyscoreCommand(redisClient
*c
) {
1003 robj
*key
= c
->argv
[1];
1006 unsigned long deleted
;
1008 /* Parse the range arguments. */
1009 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1010 addReplyError(c
,"min or max is not a double");
1014 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1015 checkType(c
,zobj
,REDIS_ZSET
)) return;
1017 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1018 zobj
->ptr
= zzlDeleteRangeByScore(zobj
->ptr
,range
,&deleted
);
1019 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1020 zset
*zs
= zobj
->ptr
;
1021 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1022 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1023 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1025 redisPanic("Unknown sorted set encoding");
1028 if (deleted
) signalModifiedKey(c
->db
,key
);
1029 server
.dirty
+= deleted
;
1030 addReplyLongLong(c
,deleted
);
1033 void zremrangebyrankCommand(redisClient
*c
) {
1034 robj
*key
= c
->argv
[1];
1039 unsigned long deleted
;
1041 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1042 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1044 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1045 checkType(c
,zobj
,REDIS_ZSET
)) return;
1047 /* Sanitize indexes. */
1048 llen
= zsetLength(zobj
);
1049 if (start
< 0) start
= llen
+start
;
1050 if (end
< 0) end
= llen
+end
;
1051 if (start
< 0) start
= 0;
1053 /* Invariant: start >= 0, so this test will be true when end < 0.
1054 * The range is empty when start > end or start >= length. */
1055 if (start
> end
|| start
>= llen
) {
1056 addReply(c
,shared
.czero
);
1059 if (end
>= llen
) end
= llen
-1;
1061 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1062 /* Correct for 1-based rank. */
1063 zobj
->ptr
= zzlDeleteRangeByRank(zobj
->ptr
,start
+1,end
+1,&deleted
);
1064 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1065 zset
*zs
= zobj
->ptr
;
1067 /* Correct for 1-based rank. */
1068 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1069 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1070 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1072 redisPanic("Unknown sorted set encoding");
1075 if (deleted
) signalModifiedKey(c
->db
,key
);
1076 server
.dirty
+= deleted
;
1077 addReplyLongLong(c
,deleted
);
1082 int type
; /* Set, sorted set */
1087 /* Set iterators. */
1100 /* Sorted set iterators. */
1104 unsigned char *eptr
, *sptr
;
1108 zskiplistNode
*node
;
1115 /* Use dirty flags for pointers that need to be cleaned up in the next
1116 * iteration over the zsetopval. The dirty flag for the long long value is
1117 * special, since long long values don't need cleanup. Instead, it means that
1118 * we already checked that "ell" holds a long long, or tried to convert another
1119 * representation into a long long value. When this was successful,
1120 * OPVAL_VALID_LL is set as well. */
1121 #define OPVAL_DIRTY_ROBJ 1
1122 #define OPVAL_DIRTY_LL 2
1123 #define OPVAL_VALID_LL 4
1125 /* Store value retrieved from the iterator. */
1128 unsigned char _buf
[32]; /* Private buffer. */
1130 unsigned char *estr
;
1136 typedef union _iterset iterset
;
1137 typedef union _iterzset iterzset
;
1139 void zuiInitIterator(zsetopsrc
*op
) {
1140 if (op
->subject
== NULL
)
1143 if (op
->type
== REDIS_SET
) {
1144 iterset
*it
= &op
->iter
.set
;
1145 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1146 it
->is
.is
= op
->subject
->ptr
;
1148 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1149 it
->ht
.dict
= op
->subject
->ptr
;
1150 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1151 it
->ht
.de
= dictNext(it
->ht
.di
);
1153 redisPanic("Unknown set encoding");
1155 } else if (op
->type
== REDIS_ZSET
) {
1156 iterzset
*it
= &op
->iter
.zset
;
1157 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1158 it
->zl
.zl
= op
->subject
->ptr
;
1159 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1160 if (it
->zl
.eptr
!= NULL
) {
1161 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1162 redisAssert(it
->zl
.sptr
!= NULL
);
1164 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1165 it
->sl
.zs
= op
->subject
->ptr
;
1166 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1168 redisPanic("Unknown sorted set encoding");
1171 redisPanic("Unsupported type");
1175 void zuiClearIterator(zsetopsrc
*op
) {
1176 if (op
->subject
== NULL
)
1179 if (op
->type
== REDIS_SET
) {
1180 iterset
*it
= &op
->iter
.set
;
1181 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1182 REDIS_NOTUSED(it
); /* skip */
1183 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1184 dictReleaseIterator(it
->ht
.di
);
1186 redisPanic("Unknown set encoding");
1188 } else if (op
->type
== REDIS_ZSET
) {
1189 iterzset
*it
= &op
->iter
.zset
;
1190 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1191 REDIS_NOTUSED(it
); /* skip */
1192 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1193 REDIS_NOTUSED(it
); /* skip */
1195 redisPanic("Unknown sorted set encoding");
1198 redisPanic("Unsupported type");
1202 int zuiLength(zsetopsrc
*op
) {
1203 if (op
->subject
== NULL
)
1206 if (op
->type
== REDIS_SET
) {
1207 iterset
*it
= &op
->iter
.set
;
1208 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1209 return intsetLen(it
->is
.is
);
1210 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1211 return dictSize(it
->ht
.dict
);
1213 redisPanic("Unknown set encoding");
1215 } else if (op
->type
== REDIS_ZSET
) {
1216 iterzset
*it
= &op
->iter
.zset
;
1217 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1218 return zzlLength(it
->zl
.zl
);
1219 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1220 return it
->sl
.zs
->zsl
->length
;
1222 redisPanic("Unknown sorted set encoding");
1225 redisPanic("Unsupported type");
1229 /* Check if the current value is valid. If so, store it in the passed structure
1230 * and move to the next element. If not valid, this means we have reached the
1231 * end of the structure and can abort. */
1232 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1233 if (op
->subject
== NULL
)
1236 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1237 decrRefCount(val
->ele
);
1239 bzero(val
,sizeof(zsetopval
));
1241 if (op
->type
== REDIS_SET
) {
1242 iterset
*it
= &op
->iter
.set
;
1243 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1244 if (!intsetGet(it
->is
.is
,it
->is
.ii
,&val
->ell
))
1248 /* Move to next element. */
1250 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1251 if (it
->ht
.de
== NULL
)
1253 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1256 /* Move to next element. */
1257 it
->ht
.de
= dictNext(it
->ht
.di
);
1259 redisPanic("Unknown set encoding");
1261 } else if (op
->type
== REDIS_ZSET
) {
1262 iterzset
*it
= &op
->iter
.zset
;
1263 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1264 /* No need to check both, but better be explicit. */
1265 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1267 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1268 val
->score
= zzlGetScore(it
->zl
.sptr
);
1270 /* Move to next element. */
1271 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1272 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1273 if (it
->sl
.node
== NULL
)
1275 val
->ele
= it
->sl
.node
->obj
;
1276 val
->score
= it
->sl
.node
->score
;
1278 /* Move to next element. */
1279 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1281 redisPanic("Unknown sorted set encoding");
1284 redisPanic("Unsupported type");
1289 int zuiLongLongFromValue(zsetopval
*val
) {
1290 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1291 val
->flags
|= OPVAL_DIRTY_LL
;
1293 if (val
->ele
!= NULL
) {
1294 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1295 val
->ell
= (long)val
->ele
->ptr
;
1296 val
->flags
|= OPVAL_VALID_LL
;
1297 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1298 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1299 val
->flags
|= OPVAL_VALID_LL
;
1301 redisPanic("Unsupported element encoding");
1303 } else if (val
->estr
!= NULL
) {
1304 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1305 val
->flags
|= OPVAL_VALID_LL
;
1307 /* The long long was already set, flag as valid. */
1308 val
->flags
|= OPVAL_VALID_LL
;
1311 return val
->flags
& OPVAL_VALID_LL
;
1314 robj
*zuiObjectFromValue(zsetopval
*val
) {
1315 if (val
->ele
== NULL
) {
1316 if (val
->estr
!= NULL
) {
1317 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1319 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1321 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1326 int zuiBufferFromValue(zsetopval
*val
) {
1327 if (val
->estr
== NULL
) {
1328 if (val
->ele
!= NULL
) {
1329 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1330 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1331 val
->estr
= val
->_buf
;
1332 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1333 val
->elen
= sdslen(val
->ele
->ptr
);
1334 val
->estr
= val
->ele
->ptr
;
1336 redisPanic("Unsupported element encoding");
1339 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1340 val
->estr
= val
->_buf
;
1346 /* Find value pointed to by val in the source pointer to by op. When found,
1347 * return 1 and store its score in target. Return 0 otherwise. */
1348 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1349 if (op
->subject
== NULL
)
1352 if (op
->type
== REDIS_SET
) {
1353 iterset
*it
= &op
->iter
.set
;
1355 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1356 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1362 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1363 zuiObjectFromValue(val
);
1364 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1371 redisPanic("Unknown set encoding");
1373 } else if (op
->type
== REDIS_ZSET
) {
1374 iterzset
*it
= &op
->iter
.zset
;
1375 zuiObjectFromValue(val
);
1377 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1378 if (zzlFind(it
->zl
.zl
,val
->ele
,score
) != NULL
) {
1379 /* Score is already set by zzlFind. */
1384 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1386 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1387 *score
= *(double*)dictGetEntryVal(de
);
1393 redisPanic("Unknown sorted set encoding");
1396 redisPanic("Unsupported type");
1400 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1401 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1404 #define REDIS_AGGR_SUM 1
1405 #define REDIS_AGGR_MIN 2
1406 #define REDIS_AGGR_MAX 3
1407 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1409 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1410 if (aggregate
== REDIS_AGGR_SUM
) {
1411 *target
= *target
+ val
;
1412 /* The result of adding two doubles is NaN when one variable
1413 * is +inf and the other is -inf. When these numbers are added,
1414 * we maintain the convention of the result being 0.0. */
1415 if (isnan(*target
)) *target
= 0.0;
1416 } else if (aggregate
== REDIS_AGGR_MIN
) {
1417 *target
= val
< *target
? val
: *target
;
1418 } else if (aggregate
== REDIS_AGGR_MAX
) {
1419 *target
= val
> *target
? val
: *target
;
1422 redisPanic("Unknown ZUNION/INTER aggregate type");
1426 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1428 int aggregate
= REDIS_AGGR_SUM
;
1432 unsigned int maxelelen
= 0;
1435 zskiplistNode
*znode
;
1438 /* expect setnum input keys to be given */
1439 setnum
= atoi(c
->argv
[2]->ptr
);
1442 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1446 /* test if the expected number of keys would overflow */
1447 if (3+setnum
> c
->argc
) {
1448 addReply(c
,shared
.syntaxerr
);
1452 /* read keys to be used for input */
1453 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1454 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1455 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1457 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1459 addReply(c
,shared
.wrongtypeerr
);
1463 src
[i
].subject
= obj
;
1464 src
[i
].type
= obj
->type
;
1465 src
[i
].encoding
= obj
->encoding
;
1467 src
[i
].subject
= NULL
;
1470 /* Default all weights to 1. */
1471 src
[i
].weight
= 1.0;
1474 /* parse optional extra arguments */
1476 int remaining
= c
->argc
- j
;
1479 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1481 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1482 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1483 "weight value is not a double") != REDIS_OK
)
1489 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1491 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1492 aggregate
= REDIS_AGGR_SUM
;
1493 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1494 aggregate
= REDIS_AGGR_MIN
;
1495 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1496 aggregate
= REDIS_AGGR_MAX
;
1499 addReply(c
,shared
.syntaxerr
);
1505 addReply(c
,shared
.syntaxerr
);
1511 for (i
= 0; i
< setnum
; i
++)
1512 zuiInitIterator(&src
[i
]);
1514 /* sort sets from the smallest to largest, this will improve our
1515 * algorithm's performance */
1516 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1518 dstobj
= createZsetObject();
1519 dstzset
= dstobj
->ptr
;
1521 if (op
== REDIS_OP_INTER
) {
1522 /* Skip everything if the smallest input is empty. */
1523 if (zuiLength(&src
[0]) > 0) {
1524 /* Precondition: as src[0] is non-empty and the inputs are ordered
1525 * by size, all src[i > 0] are non-empty too. */
1526 while (zuiNext(&src
[0],&zval
)) {
1527 double score
, value
;
1529 score
= src
[0].weight
* zval
.score
;
1530 for (j
= 1; j
< setnum
; j
++) {
1531 if (zuiFind(&src
[j
],&zval
,&value
)) {
1532 value
*= src
[j
].weight
;
1533 zunionInterAggregate(&score
,value
,aggregate
);
1539 /* Only continue when present in every input. */
1541 tmp
= zuiObjectFromValue(&zval
);
1542 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1543 incrRefCount(tmp
); /* added to skiplist */
1544 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1545 incrRefCount(tmp
); /* added to dictionary */
1547 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1548 if (sdslen(tmp
->ptr
) > maxelelen
)
1549 maxelelen
= sdslen(tmp
->ptr
);
1553 } else if (op
== REDIS_OP_UNION
) {
1554 for (i
= 0; i
< setnum
; i
++) {
1555 if (zuiLength(&src
[0]) == 0)
1558 while (zuiNext(&src
[i
],&zval
)) {
1559 double score
, value
;
1561 /* Skip key when already processed */
1562 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1565 /* Initialize score */
1566 score
= src
[i
].weight
* zval
.score
;
1568 /* Because the inputs are sorted by size, it's only possible
1569 * for sets at larger indices to hold this element. */
1570 for (j
= (i
+1); j
< setnum
; j
++) {
1571 if (zuiFind(&src
[j
],&zval
,&value
)) {
1572 value
*= src
[j
].weight
;
1573 zunionInterAggregate(&score
,value
,aggregate
);
1577 tmp
= zuiObjectFromValue(&zval
);
1578 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1579 incrRefCount(zval
.ele
); /* added to skiplist */
1580 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1581 incrRefCount(zval
.ele
); /* added to dictionary */
1583 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1584 if (sdslen(tmp
->ptr
) > maxelelen
)
1585 maxelelen
= sdslen(tmp
->ptr
);
1589 redisPanic("Unknown operator");
1592 for (i
= 0; i
< setnum
; i
++)
1593 zuiClearIterator(&src
[i
]);
1595 if (dbDelete(c
->db
,dstkey
)) {
1596 signalModifiedKey(c
->db
,dstkey
);
1600 if (dstzset
->zsl
->length
) {
1601 /* Convert to ziplist when in limits. */
1602 if (dstzset
->zsl
->length
<= server
.zset_max_ziplist_entries
&&
1603 maxelelen
<= server
.zset_max_ziplist_value
)
1604 zsetConvert(dstobj
,REDIS_ENCODING_ZIPLIST
);
1606 dbAdd(c
->db
,dstkey
,dstobj
);
1607 addReplyLongLong(c
,zsetLength(dstobj
));
1608 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1611 decrRefCount(dstobj
);
1612 addReply(c
,shared
.czero
);
1617 void zunionstoreCommand(redisClient
*c
) {
1618 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1621 void zinterstoreCommand(redisClient
*c
) {
1622 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1625 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1626 robj
*key
= c
->argv
[1];
1634 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1635 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1637 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1639 } else if (c
->argc
>= 5) {
1640 addReply(c
,shared
.syntaxerr
);
1644 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1645 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1647 /* Sanitize indexes. */
1648 llen
= zsetLength(zobj
);
1649 if (start
< 0) start
= llen
+start
;
1650 if (end
< 0) end
= llen
+end
;
1651 if (start
< 0) start
= 0;
1653 /* Invariant: start >= 0, so this test will be true when end < 0.
1654 * The range is empty when start > end or start >= length. */
1655 if (start
> end
|| start
>= llen
) {
1656 addReply(c
,shared
.emptymultibulk
);
1659 if (end
>= llen
) end
= llen
-1;
1660 rangelen
= (end
-start
)+1;
1662 /* Return the result in form of a multi-bulk reply */
1663 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1665 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1666 unsigned char *zl
= zobj
->ptr
;
1667 unsigned char *eptr
, *sptr
;
1668 unsigned char *vstr
;
1673 eptr
= ziplistIndex(zl
,-2-(2*start
));
1675 eptr
= ziplistIndex(zl
,2*start
);
1677 redisAssert(eptr
!= NULL
);
1678 sptr
= ziplistNext(zl
,eptr
);
1680 while (rangelen
--) {
1681 redisAssert(eptr
!= NULL
&& sptr
!= NULL
);
1682 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1684 addReplyBulkLongLong(c
,vlong
);
1686 addReplyBulkCBuffer(c
,vstr
,vlen
);
1689 addReplyDouble(c
,zzlGetScore(sptr
));
1692 zzlPrev(zl
,&eptr
,&sptr
);
1694 zzlNext(zl
,&eptr
,&sptr
);
1697 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1698 zset
*zs
= zobj
->ptr
;
1699 zskiplist
*zsl
= zs
->zsl
;
1703 /* Check if starting point is trivial, before doing log(N) lookup. */
1707 ln
= zslGetElementByRank(zsl
,llen
-start
);
1709 ln
= zsl
->header
->level
[0].forward
;
1711 ln
= zslGetElementByRank(zsl
,start
+1);
1715 redisAssert(ln
!= NULL
);
1717 addReplyBulk(c
,ele
);
1719 addReplyDouble(c
,ln
->score
);
1720 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1723 redisPanic("Unknown sorted set encoding");
1727 void zrangeCommand(redisClient
*c
) {
1728 zrangeGenericCommand(c
,0);
1731 void zrevrangeCommand(redisClient
*c
) {
1732 zrangeGenericCommand(c
,1);
1735 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1736 * If "justcount", only the number of elements in the range is returned. */
1737 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1739 robj
*key
= c
->argv
[1];
1740 robj
*emptyreply
, *zobj
;
1741 int offset
= 0, limit
= -1;
1743 unsigned long rangelen
= 0;
1744 void *replylen
= NULL
;
1747 /* Parse the range arguments. */
1749 /* Range is given as [max,min] */
1750 maxidx
= 2; minidx
= 3;
1752 /* Range is given as [min,max] */
1753 minidx
= 2; maxidx
= 3;
1756 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1757 addReplyError(c
,"min or max is not a double");
1761 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1762 * 4 arguments, so we'll never enter the following code path. */
1764 int remaining
= c
->argc
- 4;
1768 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1771 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1772 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1773 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1774 pos
+= 3; remaining
-= 3;
1776 addReply(c
,shared
.syntaxerr
);
1782 /* Ok, lookup the key and get the range */
1783 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1784 if ((zobj
= lookupKeyReadOrReply(c
,key
,emptyreply
)) == NULL
||
1785 checkType(c
,zobj
,REDIS_ZSET
)) return;
1787 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1788 unsigned char *zl
= zobj
->ptr
;
1789 unsigned char *eptr
, *sptr
;
1790 unsigned char *vstr
;
1795 /* If reversed, get the last node in range as starting point. */
1797 eptr
= zzlLastInRange(zl
,range
);
1799 eptr
= zzlFirstInRange(zl
,range
);
1801 /* No "first" element in the specified interval. */
1803 addReply(c
,emptyreply
);
1807 /* Get score pointer for the first element. */
1808 redisAssert(eptr
!= NULL
);
1809 sptr
= ziplistNext(zl
,eptr
);
1811 /* We don't know in advance how many matching elements there are in the
1812 * list, so we push this object that will represent the multi-bulk
1813 * length in the output buffer, and will "fix" it later */
1815 replylen
= addDeferredMultiBulkLength(c
);
1817 /* If there is an offset, just traverse the number of elements without
1818 * checking the score because that is done in the next loop. */
1819 while (eptr
&& offset
--)
1821 zzlPrev(zl
,&eptr
,&sptr
);
1823 zzlNext(zl
,&eptr
,&sptr
);
1825 while (eptr
&& limit
--) {
1826 score
= zzlGetScore(sptr
);
1828 /* Abort when the node is no longer in range. */
1830 if (!zslValueGteMin(score
,&range
)) break;
1832 if (!zslValueLteMax(score
,&range
)) break;
1838 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1840 addReplyBulkLongLong(c
,vlong
);
1842 addReplyBulkCBuffer(c
,vstr
,vlen
);
1845 addReplyDouble(c
,score
);
1848 /* Move to next node */
1850 zzlPrev(zl
,&eptr
,&sptr
);
1852 zzlNext(zl
,&eptr
,&sptr
);
1854 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1855 zset
*zs
= zobj
->ptr
;
1856 zskiplist
*zsl
= zs
->zsl
;
1859 /* If reversed, get the last node in range as starting point. */
1861 ln
= zslLastInRange(zsl
,range
);
1863 ln
= zslFirstInRange(zsl
,range
);
1865 /* No "first" element in the specified interval. */
1867 addReply(c
,emptyreply
);
1871 /* We don't know in advance how many matching elements there are in the
1872 * list, so we push this object that will represent the multi-bulk
1873 * length in the output buffer, and will "fix" it later */
1875 replylen
= addDeferredMultiBulkLength(c
);
1877 /* If there is an offset, just traverse the number of elements without
1878 * checking the score because that is done in the next loop. */
1879 while (ln
&& offset
--)
1880 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1882 while (ln
&& limit
--) {
1883 /* Abort when the node is no longer in range. */
1885 if (!zslValueGteMin(ln
->score
,&range
)) break;
1887 if (!zslValueLteMax(ln
->score
,&range
)) break;
1893 addReplyBulk(c
,ln
->obj
);
1895 addReplyDouble(c
,ln
->score
);
1898 /* Move to next node */
1899 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1902 redisPanic("Unknown sorted set encoding");
1906 addReplyLongLong(c
,(long)rangelen
);
1908 if (withscores
) rangelen
*= 2;
1909 setDeferredMultiBulkLength(c
,replylen
,rangelen
);
1913 void zrangebyscoreCommand(redisClient
*c
) {
1914 genericZrangebyscoreCommand(c
,0,0);
1917 void zrevrangebyscoreCommand(redisClient
*c
) {
1918 genericZrangebyscoreCommand(c
,1,0);
1921 void zcountCommand(redisClient
*c
) {
1922 genericZrangebyscoreCommand(c
,0,1);
1925 void zcardCommand(redisClient
*c
) {
1926 robj
*key
= c
->argv
[1];
1929 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
1930 checkType(c
,zobj
,REDIS_ZSET
)) return;
1932 addReplyLongLong(c
,zsetLength(zobj
));
1935 void zscoreCommand(redisClient
*c
) {
1936 robj
*key
= c
->argv
[1];
1940 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1941 checkType(c
,zobj
,REDIS_ZSET
)) return;
1943 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1944 if (zzlFind(zobj
->ptr
,c
->argv
[2],&score
) != NULL
)
1945 addReplyDouble(c
,score
);
1947 addReply(c
,shared
.nullbulk
);
1948 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1949 zset
*zs
= zobj
->ptr
;
1952 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1953 de
= dictFind(zs
->dict
,c
->argv
[2]);
1955 score
= *(double*)dictGetEntryVal(de
);
1956 addReplyDouble(c
,score
);
1958 addReply(c
,shared
.nullbulk
);
1961 redisPanic("Unknown sorted set encoding");
1965 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1966 robj
*key
= c
->argv
[1];
1967 robj
*ele
= c
->argv
[2];
1972 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1973 checkType(c
,zobj
,REDIS_ZSET
)) return;
1974 llen
= zsetLength(zobj
);
1976 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
1977 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1978 unsigned char *zl
= zobj
->ptr
;
1979 unsigned char *eptr
, *sptr
;
1981 eptr
= ziplistIndex(zl
,0);
1982 redisAssert(eptr
!= NULL
);
1983 sptr
= ziplistNext(zl
,eptr
);
1984 redisAssert(sptr
!= NULL
);
1987 while(eptr
!= NULL
) {
1988 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
1991 zzlNext(zl
,&eptr
,&sptr
);
1996 addReplyLongLong(c
,llen
-rank
);
1998 addReplyLongLong(c
,rank
-1);
2000 addReply(c
,shared
.nullbulk
);
2002 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
2003 zset
*zs
= zobj
->ptr
;
2004 zskiplist
*zsl
= zs
->zsl
;
2008 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2009 de
= dictFind(zs
->dict
,ele
);
2011 score
= *(double*)dictGetEntryVal(de
);
2012 rank
= zslGetRank(zsl
,score
,ele
);
2013 redisAssert(rank
); /* Existing elements always have a rank. */
2015 addReplyLongLong(c
,llen
-rank
);
2017 addReplyLongLong(c
,rank
-1);
2019 addReply(c
,shared
.nullbulk
);
2022 redisPanic("Unknown sorted set encoding");
2026 void zrankCommand(redisClient
*c
) {
2027 zrankGenericCommand(c
, 0);
2030 void zrevrankCommand(redisClient
*c
) {
2031 zrankGenericCommand(c
, 1);