]>
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 static int zslValueGteMin(double value
, zrangespec
*spec
) {
178 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
181 static int zslValueLteMax(double value
, zrangespec
*spec
) {
182 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
185 /* Returns if there is a part of the zset is in range. */
186 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
189 /* Test for ranges that will always be empty. */
190 if (range
->min
> range
->max
||
191 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
194 if (x
== NULL
|| !zslValueGteMin(x
->score
,range
))
196 x
= zsl
->header
->level
[0].forward
;
197 if (x
== NULL
|| !zslValueLteMax(x
->score
,range
))
202 /* Find the first node that is contained in the specified range.
203 * Returns NULL when no element is contained in the range. */
204 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
208 /* If everything is out of range, return early. */
209 if (!zslIsInRange(zsl
,&range
)) return NULL
;
212 for (i
= zsl
->level
-1; i
>= 0; i
--) {
213 /* Go forward while *OUT* of range. */
214 while (x
->level
[i
].forward
&&
215 !zslValueGteMin(x
->level
[i
].forward
->score
,&range
))
216 x
= x
->level
[i
].forward
;
219 /* This is an inner range, so the next node cannot be NULL. */
220 x
= x
->level
[0].forward
;
221 redisAssert(x
!= NULL
);
223 /* Check if score <= max. */
224 if (!zslValueLteMax(x
->score
,&range
)) return NULL
;
228 /* Find the last node that is contained in the specified range.
229 * Returns NULL when no element is contained in the range. */
230 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
234 /* If everything is out of range, return early. */
235 if (!zslIsInRange(zsl
,&range
)) return NULL
;
238 for (i
= zsl
->level
-1; i
>= 0; i
--) {
239 /* Go forward while *IN* range. */
240 while (x
->level
[i
].forward
&&
241 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
242 x
= x
->level
[i
].forward
;
245 /* This is an inner range, so this node cannot be NULL. */
246 redisAssert(x
!= NULL
);
248 /* Check if score >= min. */
249 if (!zslValueGteMin(x
->score
,&range
)) return NULL
;
253 /* Delete all the elements with score between min and max from the skiplist.
254 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
255 * Note that this function takes the reference to the hash table view of the
256 * sorted set, in order to remove the elements from the hash table too. */
257 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
258 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
259 unsigned long removed
= 0;
263 for (i
= zsl
->level
-1; i
>= 0; i
--) {
264 while (x
->level
[i
].forward
&& (range
.minex
?
265 x
->level
[i
].forward
->score
<= range
.min
:
266 x
->level
[i
].forward
->score
< range
.min
))
267 x
= x
->level
[i
].forward
;
271 /* Current node is the last with score < or <= min. */
272 x
= x
->level
[0].forward
;
274 /* Delete nodes while in range. */
275 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
276 zskiplistNode
*next
= x
->level
[0].forward
;
277 zslDeleteNode(zsl
,x
,update
);
278 dictDelete(dict
,x
->obj
);
286 /* Delete all the elements with rank between start and end from the skiplist.
287 * Start and end are inclusive. Note that start and end need to be 1-based */
288 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
289 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
290 unsigned long traversed
= 0, removed
= 0;
294 for (i
= zsl
->level
-1; i
>= 0; i
--) {
295 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
296 traversed
+= x
->level
[i
].span
;
297 x
= x
->level
[i
].forward
;
303 x
= x
->level
[0].forward
;
304 while (x
&& traversed
<= end
) {
305 zskiplistNode
*next
= x
->level
[0].forward
;
306 zslDeleteNode(zsl
,x
,update
);
307 dictDelete(dict
,x
->obj
);
316 /* Find the rank for an element by both score and key.
317 * Returns 0 when the element cannot be found, rank otherwise.
318 * Note that the rank is 1-based due to the span of zsl->header to the
320 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
322 unsigned long rank
= 0;
326 for (i
= zsl
->level
-1; i
>= 0; i
--) {
327 while (x
->level
[i
].forward
&&
328 (x
->level
[i
].forward
->score
< score
||
329 (x
->level
[i
].forward
->score
== score
&&
330 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
331 rank
+= x
->level
[i
].span
;
332 x
= x
->level
[i
].forward
;
335 /* x might be equal to zsl->header, so test if obj is non-NULL */
336 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
343 /* Finds an element by its rank. The rank argument needs to be 1-based. */
344 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
346 unsigned long traversed
= 0;
350 for (i
= zsl
->level
-1; i
>= 0; i
--) {
351 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
353 traversed
+= x
->level
[i
].span
;
354 x
= x
->level
[i
].forward
;
356 if (traversed
== rank
) {
363 /* Populate the rangespec according to the objects min and max. */
364 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
366 spec
->minex
= spec
->maxex
= 0;
368 /* Parse the min-max interval. If one of the values is prefixed
369 * by the "(" character, it's considered "open". For instance
370 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
371 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
372 if (min
->encoding
== REDIS_ENCODING_INT
) {
373 spec
->min
= (long)min
->ptr
;
375 if (((char*)min
->ptr
)[0] == '(') {
376 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
377 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
380 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
381 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
384 if (max
->encoding
== REDIS_ENCODING_INT
) {
385 spec
->max
= (long)max
->ptr
;
387 if (((char*)max
->ptr
)[0] == '(') {
388 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
389 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
392 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
393 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
400 /*-----------------------------------------------------------------------------
401 * Ziplist-backed sorted set API
402 *----------------------------------------------------------------------------*/
404 double zzlGetScore(unsigned char *sptr
) {
411 redisAssert(sptr
!= NULL
);
412 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
415 memcpy(buf
,vstr
,vlen
);
417 score
= strtod(buf
,NULL
);
425 /* Compare element in sorted set with given element. */
426 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
430 unsigned char vbuf
[32];
433 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
435 /* Store string representation of long long in buf. */
436 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
440 minlen
= (vlen
< clen
) ? vlen
: clen
;
441 cmp
= memcmp(vstr
,cstr
,minlen
);
442 if (cmp
== 0) return vlen
-clen
;
446 unsigned int zzlLength(unsigned char *zl
) {
447 return ziplistLen(zl
)/2;
450 /* Move to next entry based on the values in eptr and sptr. Both are set to
451 * NULL when there is no next entry. */
452 void zzlNext(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
453 unsigned char *_eptr
, *_sptr
;
454 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
456 _eptr
= ziplistNext(zl
,*sptr
);
458 _sptr
= ziplistNext(zl
,_eptr
);
459 redisAssert(_sptr
!= NULL
);
469 /* Move to the previous entry based on the values in eptr and sptr. Both are
470 * set to NULL when there is no next entry. */
471 void zzlPrev(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
472 unsigned char *_eptr
, *_sptr
;
473 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
475 _sptr
= ziplistPrev(zl
,*eptr
);
477 _eptr
= ziplistPrev(zl
,_sptr
);
478 redisAssert(_eptr
!= NULL
);
480 /* No previous entry. */
488 /* Returns if there is a part of the zset is in range. Should only be used
489 * internally by zzlFirstInRange and zzlLastInRange. */
490 int zzlIsInRange(unsigned char *zl
, zrangespec
*range
) {
494 /* Test for ranges that will always be empty. */
495 if (range
->min
> range
->max
||
496 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
499 p
= ziplistIndex(zl
,-1); /* Last score. */
500 redisAssert(p
!= NULL
);
501 score
= zzlGetScore(p
);
502 if (!zslValueGteMin(score
,range
))
505 p
= ziplistIndex(zl
,1); /* First score. */
506 redisAssert(p
!= NULL
);
507 score
= zzlGetScore(p
);
508 if (!zslValueLteMax(score
,range
))
514 /* Find pointer to the first element contained in the specified range.
515 * Returns NULL when no element is contained in the range. */
516 unsigned char *zzlFirstInRange(unsigned char *zl
, zrangespec range
) {
517 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
520 /* If everything is out of range, return early. */
521 if (!zzlIsInRange(zl
,&range
)) return NULL
;
523 while (eptr
!= NULL
) {
524 sptr
= ziplistNext(zl
,eptr
);
525 redisAssert(sptr
!= NULL
);
527 score
= zzlGetScore(sptr
);
528 if (zslValueGteMin(score
,&range
)) {
529 /* Check if score <= max. */
530 if (zslValueLteMax(score
,&range
))
535 /* Move to next element. */
536 eptr
= ziplistNext(zl
,sptr
);
542 /* Find pointer to the last element contained in the specified range.
543 * Returns NULL when no element is contained in the range. */
544 unsigned char *zzlLastInRange(unsigned char *zl
, zrangespec range
) {
545 unsigned char *eptr
= ziplistIndex(zl
,-2), *sptr
;
548 /* If everything is out of range, return early. */
549 if (!zzlIsInRange(zl
,&range
)) return NULL
;
551 while (eptr
!= NULL
) {
552 sptr
= ziplistNext(zl
,eptr
);
553 redisAssert(sptr
!= NULL
);
555 score
= zzlGetScore(sptr
);
556 if (zslValueLteMax(score
,&range
)) {
557 /* Check if score >= min. */
558 if (zslValueGteMin(score
,&range
))
563 /* Move to previous element by moving to the score of previous element.
564 * When this returns NULL, we know there also is no element. */
565 sptr
= ziplistPrev(zl
,eptr
);
567 redisAssert((eptr
= ziplistPrev(zl
,sptr
)) != NULL
);
575 unsigned char *zzlFind(unsigned char *zl
, robj
*ele
, double *score
) {
576 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
578 ele
= getDecodedObject(ele
);
579 while (eptr
!= NULL
) {
580 sptr
= ziplistNext(zl
,eptr
);
581 redisAssertWithInfo(NULL
,ele
,sptr
!= NULL
);
583 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
584 /* Matching element, pull out score. */
585 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
590 /* Move to next element. */
591 eptr
= ziplistNext(zl
,sptr
);
598 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
599 * don't want to modify the one given as argument. */
600 unsigned char *zzlDelete(unsigned char *zl
, unsigned char *eptr
) {
601 unsigned char *p
= eptr
;
603 /* TODO: add function to ziplist API to delete N elements from offset. */
604 zl
= ziplistDelete(zl
,&p
);
605 zl
= ziplistDelete(zl
,&p
);
609 unsigned char *zzlInsertAt(unsigned char *zl
, unsigned char *eptr
, robj
*ele
, double score
) {
615 redisAssertWithInfo(NULL
,ele
,ele
->encoding
== REDIS_ENCODING_RAW
);
616 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
618 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
619 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
621 /* Keep offset relative to zl, as it might be re-allocated. */
623 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
626 /* Insert score after the element. */
627 redisAssertWithInfo(NULL
,ele
,(sptr
= ziplistNext(zl
,eptr
)) != NULL
);
628 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
634 /* Insert (element,score) pair in ziplist. This function assumes the element is
635 * not yet present in the list. */
636 unsigned char *zzlInsert(unsigned char *zl
, robj
*ele
, double score
) {
637 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
640 ele
= getDecodedObject(ele
);
641 while (eptr
!= NULL
) {
642 sptr
= ziplistNext(zl
,eptr
);
643 redisAssertWithInfo(NULL
,ele
,sptr
!= NULL
);
644 s
= zzlGetScore(sptr
);
647 /* First element with score larger than score for element to be
648 * inserted. This means we should take its spot in the list to
649 * maintain ordering. */
650 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
652 } else if (s
== score
) {
653 /* Ensure lexicographical ordering for elements. */
654 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) > 0) {
655 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
660 /* Move to next element. */
661 eptr
= ziplistNext(zl
,sptr
);
664 /* Push on tail of list when it was not yet inserted. */
666 zl
= zzlInsertAt(zl
,NULL
,ele
,score
);
672 unsigned char *zzlDeleteRangeByScore(unsigned char *zl
, zrangespec range
, unsigned long *deleted
) {
673 unsigned char *eptr
, *sptr
;
675 unsigned long num
= 0;
677 if (deleted
!= NULL
) *deleted
= 0;
679 eptr
= zzlFirstInRange(zl
,range
);
680 if (eptr
== NULL
) return zl
;
682 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
683 * byte and ziplistNext will return NULL. */
684 while ((sptr
= ziplistNext(zl
,eptr
)) != NULL
) {
685 score
= zzlGetScore(sptr
);
686 if (zslValueLteMax(score
,&range
)) {
687 /* Delete both the element and the score. */
688 zl
= ziplistDelete(zl
,&eptr
);
689 zl
= ziplistDelete(zl
,&eptr
);
692 /* No longer in range. */
697 if (deleted
!= NULL
) *deleted
= num
;
701 /* Delete all the elements with rank between start and end from the skiplist.
702 * Start and end are inclusive. Note that start and end need to be 1-based */
703 unsigned char *zzlDeleteRangeByRank(unsigned char *zl
, unsigned int start
, unsigned int end
, unsigned long *deleted
) {
704 unsigned int num
= (end
-start
)+1;
705 if (deleted
) *deleted
= num
;
706 zl
= ziplistDeleteRange(zl
,2*(start
-1),2*num
);
710 /*-----------------------------------------------------------------------------
711 * Common sorted set API
712 *----------------------------------------------------------------------------*/
714 unsigned int zsetLength(robj
*zobj
) {
716 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
717 length
= zzlLength(zobj
->ptr
);
718 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
719 length
= ((zset
*)zobj
->ptr
)->zsl
->length
;
721 redisPanic("Unknown sorted set encoding");
726 void zsetConvert(robj
*zobj
, int encoding
) {
728 zskiplistNode
*node
, *next
;
732 if (zobj
->encoding
== encoding
) return;
733 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
734 unsigned char *zl
= zobj
->ptr
;
735 unsigned char *eptr
, *sptr
;
740 if (encoding
!= REDIS_ENCODING_SKIPLIST
)
741 redisPanic("Unknown target encoding");
743 zs
= zmalloc(sizeof(*zs
));
744 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
745 zs
->zsl
= zslCreate();
747 eptr
= ziplistIndex(zl
,0);
748 redisAssertWithInfo(NULL
,zobj
,eptr
!= NULL
);
749 sptr
= ziplistNext(zl
,eptr
);
750 redisAssertWithInfo(NULL
,zobj
,sptr
!= NULL
);
752 while (eptr
!= NULL
) {
753 score
= zzlGetScore(sptr
);
754 redisAssertWithInfo(NULL
,zobj
,ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
756 ele
= createStringObjectFromLongLong(vlong
);
758 ele
= createStringObject((char*)vstr
,vlen
);
760 /* Has incremented refcount since it was just created. */
761 node
= zslInsert(zs
->zsl
,score
,ele
);
762 redisAssertWithInfo(NULL
,zobj
,dictAdd(zs
->dict
,ele
,&node
->score
) == DICT_OK
);
763 incrRefCount(ele
); /* Added to dictionary. */
764 zzlNext(zl
,&eptr
,&sptr
);
769 zobj
->encoding
= REDIS_ENCODING_SKIPLIST
;
770 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
771 unsigned char *zl
= ziplistNew();
773 if (encoding
!= REDIS_ENCODING_ZIPLIST
)
774 redisPanic("Unknown target encoding");
776 /* Approach similar to zslFree(), since we want to free the skiplist at
777 * the same time as creating the ziplist. */
779 dictRelease(zs
->dict
);
780 node
= zs
->zsl
->header
->level
[0].forward
;
781 zfree(zs
->zsl
->header
);
785 ele
= getDecodedObject(node
->obj
);
786 zl
= zzlInsertAt(zl
,NULL
,ele
,node
->score
);
789 next
= node
->level
[0].forward
;
796 zobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
798 redisPanic("Unknown sorted set encoding");
802 /*-----------------------------------------------------------------------------
803 * Sorted set commands
804 *----------------------------------------------------------------------------*/
806 /* This generic command implements both ZADD and ZINCRBY. */
807 void zaddGenericCommand(redisClient
*c
, int incr
) {
808 static char *nanerr
= "resulting score is not a number (NaN)";
809 robj
*key
= c
->argv
[1];
813 double score
= 0, *scores
, curscore
= 0.0;
814 int j
, elements
= (c
->argc
-2)/2;
818 addReply(c
,shared
.syntaxerr
);
822 /* Start parsing all the scores, we need to emit any syntax error
823 * before executing additions to the sorted set, as the command should
824 * either execute fully or nothing at all. */
825 scores
= zmalloc(sizeof(double)*elements
);
826 for (j
= 0; j
< elements
; j
++) {
827 if (getDoubleFromObjectOrReply(c
,c
->argv
[2+j
*2],&scores
[j
],NULL
)
835 /* Lookup the key and create the sorted set if does not exist. */
836 zobj
= lookupKeyWrite(c
->db
,key
);
838 if (server
.zset_max_ziplist_entries
== 0 ||
839 server
.zset_max_ziplist_value
< sdslen(c
->argv
[3]->ptr
))
841 zobj
= createZsetObject();
843 zobj
= createZsetZiplistObject();
845 dbAdd(c
->db
,key
,zobj
);
847 if (zobj
->type
!= REDIS_ZSET
) {
848 addReply(c
,shared
.wrongtypeerr
);
854 for (j
= 0; j
< elements
; j
++) {
857 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
860 /* Prefer non-encoded element when dealing with ziplists. */
861 ele
= c
->argv
[3+j
*2];
862 if ((eptr
= zzlFind(zobj
->ptr
,ele
,&curscore
)) != NULL
) {
866 addReplyError(c
,nanerr
);
867 /* Don't need to check if the sorted set is empty
868 * because we know it has at least one element. */
874 /* Remove and re-insert when score changed. */
875 if (score
!= curscore
) {
876 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
877 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
879 signalModifiedKey(c
->db
,key
);
883 /* Optimize: check if the element is too large or the list
884 * becomes too long *before* executing zzlInsert. */
885 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
886 if (zzlLength(zobj
->ptr
) > server
.zset_max_ziplist_entries
)
887 zsetConvert(zobj
,REDIS_ENCODING_SKIPLIST
);
888 if (sdslen(ele
->ptr
) > server
.zset_max_ziplist_value
)
889 zsetConvert(zobj
,REDIS_ENCODING_SKIPLIST
);
891 signalModifiedKey(c
->db
,key
);
895 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
896 zset
*zs
= zobj
->ptr
;
897 zskiplistNode
*znode
;
900 ele
= c
->argv
[3+j
*2] = tryObjectEncoding(c
->argv
[3+j
*2]);
901 de
= dictFind(zs
->dict
,ele
);
903 curobj
= dictGetEntryKey(de
);
904 curscore
= *(double*)dictGetEntryVal(de
);
909 addReplyError(c
,nanerr
);
910 /* Don't need to check if the sorted set is empty
911 * because we know it has at least one element. */
917 /* Remove and re-insert when score changed. We can safely
918 * delete the key object from the skiplist, since the
919 * dictionary still has a reference to it. */
920 if (score
!= curscore
) {
921 redisAssertWithInfo(c
,curobj
,zslDelete(zs
->zsl
,curscore
,curobj
));
922 znode
= zslInsert(zs
->zsl
,score
,curobj
);
923 incrRefCount(curobj
); /* Re-inserted in skiplist. */
924 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
926 signalModifiedKey(c
->db
,key
);
930 znode
= zslInsert(zs
->zsl
,score
,ele
);
931 incrRefCount(ele
); /* Inserted in skiplist. */
932 redisAssertWithInfo(c
,curobj
,dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
933 incrRefCount(ele
); /* Added to dictionary. */
935 signalModifiedKey(c
->db
,key
);
940 redisPanic("Unknown sorted set encoding");
944 if (incr
) /* ZINCRBY */
945 addReplyDouble(c
,score
);
947 addReplyLongLong(c
,added
);
950 void zaddCommand(redisClient
*c
) {
951 zaddGenericCommand(c
,0);
954 void zincrbyCommand(redisClient
*c
) {
955 zaddGenericCommand(c
,1);
958 void zremCommand(redisClient
*c
) {
959 robj
*key
= c
->argv
[1];
963 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
964 checkType(c
,zobj
,REDIS_ZSET
)) return;
966 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
969 for (j
= 2; j
< c
->argc
; j
++) {
970 if ((eptr
= zzlFind(zobj
->ptr
,c
->argv
[j
],NULL
)) != NULL
) {
972 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
973 if (zzlLength(zobj
->ptr
) == 0) {
979 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
980 zset
*zs
= zobj
->ptr
;
984 for (j
= 2; j
< c
->argc
; j
++) {
985 de
= dictFind(zs
->dict
,c
->argv
[j
]);
989 /* Delete from the skiplist */
990 score
= *(double*)dictGetEntryVal(de
);
991 redisAssertWithInfo(c
,c
->argv
[j
],zslDelete(zs
->zsl
,score
,c
->argv
[j
]));
993 /* Delete from the hash table */
994 dictDelete(zs
->dict
,c
->argv
[j
]);
995 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
996 if (dictSize(zs
->dict
) == 0) {
1003 redisPanic("Unknown sorted set encoding");
1007 signalModifiedKey(c
->db
,key
);
1008 server
.dirty
+= deleted
;
1010 addReplyLongLong(c
,deleted
);
1013 void zremrangebyscoreCommand(redisClient
*c
) {
1014 robj
*key
= c
->argv
[1];
1017 unsigned long deleted
;
1019 /* Parse the range arguments. */
1020 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1021 addReplyError(c
,"min or max is not a double");
1025 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1026 checkType(c
,zobj
,REDIS_ZSET
)) return;
1028 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1029 zobj
->ptr
= zzlDeleteRangeByScore(zobj
->ptr
,range
,&deleted
);
1030 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1031 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1032 zset
*zs
= zobj
->ptr
;
1033 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1034 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1035 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1037 redisPanic("Unknown sorted set encoding");
1040 if (deleted
) signalModifiedKey(c
->db
,key
);
1041 server
.dirty
+= deleted
;
1042 addReplyLongLong(c
,deleted
);
1045 void zremrangebyrankCommand(redisClient
*c
) {
1046 robj
*key
= c
->argv
[1];
1051 unsigned long deleted
;
1053 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1054 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1056 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1057 checkType(c
,zobj
,REDIS_ZSET
)) return;
1059 /* Sanitize indexes. */
1060 llen
= zsetLength(zobj
);
1061 if (start
< 0) start
= llen
+start
;
1062 if (end
< 0) end
= llen
+end
;
1063 if (start
< 0) start
= 0;
1065 /* Invariant: start >= 0, so this test will be true when end < 0.
1066 * The range is empty when start > end or start >= length. */
1067 if (start
> end
|| start
>= llen
) {
1068 addReply(c
,shared
.czero
);
1071 if (end
>= llen
) end
= llen
-1;
1073 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1074 /* Correct for 1-based rank. */
1075 zobj
->ptr
= zzlDeleteRangeByRank(zobj
->ptr
,start
+1,end
+1,&deleted
);
1076 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1077 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1078 zset
*zs
= zobj
->ptr
;
1080 /* Correct for 1-based rank. */
1081 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1082 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1083 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1085 redisPanic("Unknown sorted set encoding");
1088 if (deleted
) signalModifiedKey(c
->db
,key
);
1089 server
.dirty
+= deleted
;
1090 addReplyLongLong(c
,deleted
);
1095 int type
; /* Set, sorted set */
1100 /* Set iterators. */
1113 /* Sorted set iterators. */
1117 unsigned char *eptr
, *sptr
;
1121 zskiplistNode
*node
;
1128 /* Use dirty flags for pointers that need to be cleaned up in the next
1129 * iteration over the zsetopval. The dirty flag for the long long value is
1130 * special, since long long values don't need cleanup. Instead, it means that
1131 * we already checked that "ell" holds a long long, or tried to convert another
1132 * representation into a long long value. When this was successful,
1133 * OPVAL_VALID_LL is set as well. */
1134 #define OPVAL_DIRTY_ROBJ 1
1135 #define OPVAL_DIRTY_LL 2
1136 #define OPVAL_VALID_LL 4
1138 /* Store value retrieved from the iterator. */
1141 unsigned char _buf
[32]; /* Private buffer. */
1143 unsigned char *estr
;
1149 typedef union _iterset iterset
;
1150 typedef union _iterzset iterzset
;
1152 void zuiInitIterator(zsetopsrc
*op
) {
1153 if (op
->subject
== NULL
)
1156 if (op
->type
== REDIS_SET
) {
1157 iterset
*it
= &op
->iter
.set
;
1158 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1159 it
->is
.is
= op
->subject
->ptr
;
1161 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1162 it
->ht
.dict
= op
->subject
->ptr
;
1163 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1164 it
->ht
.de
= dictNext(it
->ht
.di
);
1166 redisPanic("Unknown set encoding");
1168 } else if (op
->type
== REDIS_ZSET
) {
1169 iterzset
*it
= &op
->iter
.zset
;
1170 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1171 it
->zl
.zl
= op
->subject
->ptr
;
1172 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1173 if (it
->zl
.eptr
!= NULL
) {
1174 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1175 redisAssert(it
->zl
.sptr
!= NULL
);
1177 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1178 it
->sl
.zs
= op
->subject
->ptr
;
1179 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1181 redisPanic("Unknown sorted set encoding");
1184 redisPanic("Unsupported type");
1188 void zuiClearIterator(zsetopsrc
*op
) {
1189 if (op
->subject
== NULL
)
1192 if (op
->type
== REDIS_SET
) {
1193 iterset
*it
= &op
->iter
.set
;
1194 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1195 REDIS_NOTUSED(it
); /* skip */
1196 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1197 dictReleaseIterator(it
->ht
.di
);
1199 redisPanic("Unknown set encoding");
1201 } else if (op
->type
== REDIS_ZSET
) {
1202 iterzset
*it
= &op
->iter
.zset
;
1203 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1204 REDIS_NOTUSED(it
); /* skip */
1205 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1206 REDIS_NOTUSED(it
); /* skip */
1208 redisPanic("Unknown sorted set encoding");
1211 redisPanic("Unsupported type");
1215 int zuiLength(zsetopsrc
*op
) {
1216 if (op
->subject
== NULL
)
1219 if (op
->type
== REDIS_SET
) {
1220 iterset
*it
= &op
->iter
.set
;
1221 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1222 return intsetLen(it
->is
.is
);
1223 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1224 return dictSize(it
->ht
.dict
);
1226 redisPanic("Unknown set encoding");
1228 } else if (op
->type
== REDIS_ZSET
) {
1229 iterzset
*it
= &op
->iter
.zset
;
1230 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1231 return zzlLength(it
->zl
.zl
);
1232 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1233 return it
->sl
.zs
->zsl
->length
;
1235 redisPanic("Unknown sorted set encoding");
1238 redisPanic("Unsupported type");
1242 /* Check if the current value is valid. If so, store it in the passed structure
1243 * and move to the next element. If not valid, this means we have reached the
1244 * end of the structure and can abort. */
1245 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1246 if (op
->subject
== NULL
)
1249 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1250 decrRefCount(val
->ele
);
1252 bzero(val
,sizeof(zsetopval
));
1254 if (op
->type
== REDIS_SET
) {
1255 iterset
*it
= &op
->iter
.set
;
1256 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1257 if (!intsetGet(it
->is
.is
,it
->is
.ii
,(int64_t*)&val
->ell
))
1261 /* Move to next element. */
1263 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1264 if (it
->ht
.de
== NULL
)
1266 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1269 /* Move to next element. */
1270 it
->ht
.de
= dictNext(it
->ht
.di
);
1272 redisPanic("Unknown set encoding");
1274 } else if (op
->type
== REDIS_ZSET
) {
1275 iterzset
*it
= &op
->iter
.zset
;
1276 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1277 /* No need to check both, but better be explicit. */
1278 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1280 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1281 val
->score
= zzlGetScore(it
->zl
.sptr
);
1283 /* Move to next element. */
1284 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1285 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1286 if (it
->sl
.node
== NULL
)
1288 val
->ele
= it
->sl
.node
->obj
;
1289 val
->score
= it
->sl
.node
->score
;
1291 /* Move to next element. */
1292 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1294 redisPanic("Unknown sorted set encoding");
1297 redisPanic("Unsupported type");
1302 int zuiLongLongFromValue(zsetopval
*val
) {
1303 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1304 val
->flags
|= OPVAL_DIRTY_LL
;
1306 if (val
->ele
!= NULL
) {
1307 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1308 val
->ell
= (long)val
->ele
->ptr
;
1309 val
->flags
|= OPVAL_VALID_LL
;
1310 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1311 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1312 val
->flags
|= OPVAL_VALID_LL
;
1314 redisPanic("Unsupported element encoding");
1316 } else if (val
->estr
!= NULL
) {
1317 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1318 val
->flags
|= OPVAL_VALID_LL
;
1320 /* The long long was already set, flag as valid. */
1321 val
->flags
|= OPVAL_VALID_LL
;
1324 return val
->flags
& OPVAL_VALID_LL
;
1327 robj
*zuiObjectFromValue(zsetopval
*val
) {
1328 if (val
->ele
== NULL
) {
1329 if (val
->estr
!= NULL
) {
1330 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1332 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1334 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1339 int zuiBufferFromValue(zsetopval
*val
) {
1340 if (val
->estr
== NULL
) {
1341 if (val
->ele
!= NULL
) {
1342 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1343 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1344 val
->estr
= val
->_buf
;
1345 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1346 val
->elen
= sdslen(val
->ele
->ptr
);
1347 val
->estr
= val
->ele
->ptr
;
1349 redisPanic("Unsupported element encoding");
1352 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1353 val
->estr
= val
->_buf
;
1359 /* Find value pointed to by val in the source pointer to by op. When found,
1360 * return 1 and store its score in target. Return 0 otherwise. */
1361 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1362 if (op
->subject
== NULL
)
1365 if (op
->type
== REDIS_SET
) {
1366 iterset
*it
= &op
->iter
.set
;
1368 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1369 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1375 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1376 zuiObjectFromValue(val
);
1377 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1384 redisPanic("Unknown set encoding");
1386 } else if (op
->type
== REDIS_ZSET
) {
1387 iterzset
*it
= &op
->iter
.zset
;
1388 zuiObjectFromValue(val
);
1390 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1391 if (zzlFind(it
->zl
.zl
,val
->ele
,score
) != NULL
) {
1392 /* Score is already set by zzlFind. */
1397 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1399 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1400 *score
= *(double*)dictGetEntryVal(de
);
1406 redisPanic("Unknown sorted set encoding");
1409 redisPanic("Unsupported type");
1413 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1414 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1417 #define REDIS_AGGR_SUM 1
1418 #define REDIS_AGGR_MIN 2
1419 #define REDIS_AGGR_MAX 3
1420 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1422 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1423 if (aggregate
== REDIS_AGGR_SUM
) {
1424 *target
= *target
+ val
;
1425 /* The result of adding two doubles is NaN when one variable
1426 * is +inf and the other is -inf. When these numbers are added,
1427 * we maintain the convention of the result being 0.0. */
1428 if (isnan(*target
)) *target
= 0.0;
1429 } else if (aggregate
== REDIS_AGGR_MIN
) {
1430 *target
= val
< *target
? val
: *target
;
1431 } else if (aggregate
== REDIS_AGGR_MAX
) {
1432 *target
= val
> *target
? val
: *target
;
1435 redisPanic("Unknown ZUNION/INTER aggregate type");
1439 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1441 int aggregate
= REDIS_AGGR_SUM
;
1445 unsigned int maxelelen
= 0;
1448 zskiplistNode
*znode
;
1451 /* expect setnum input keys to be given */
1452 setnum
= atoi(c
->argv
[2]->ptr
);
1455 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1459 /* test if the expected number of keys would overflow */
1460 if (3+setnum
> c
->argc
) {
1461 addReply(c
,shared
.syntaxerr
);
1465 /* read keys to be used for input */
1466 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1467 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1468 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1470 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1472 addReply(c
,shared
.wrongtypeerr
);
1476 src
[i
].subject
= obj
;
1477 src
[i
].type
= obj
->type
;
1478 src
[i
].encoding
= obj
->encoding
;
1480 src
[i
].subject
= NULL
;
1483 /* Default all weights to 1. */
1484 src
[i
].weight
= 1.0;
1487 /* parse optional extra arguments */
1489 int remaining
= c
->argc
- j
;
1492 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1494 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1495 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1496 "weight value is not a double") != REDIS_OK
)
1502 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1504 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1505 aggregate
= REDIS_AGGR_SUM
;
1506 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1507 aggregate
= REDIS_AGGR_MIN
;
1508 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1509 aggregate
= REDIS_AGGR_MAX
;
1512 addReply(c
,shared
.syntaxerr
);
1518 addReply(c
,shared
.syntaxerr
);
1524 for (i
= 0; i
< setnum
; i
++)
1525 zuiInitIterator(&src
[i
]);
1527 /* sort sets from the smallest to largest, this will improve our
1528 * algorithm's performance */
1529 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1531 dstobj
= createZsetObject();
1532 dstzset
= dstobj
->ptr
;
1533 memset(&zval
, 0, sizeof(zval
));
1535 if (op
== REDIS_OP_INTER
) {
1536 /* Skip everything if the smallest input is empty. */
1537 if (zuiLength(&src
[0]) > 0) {
1538 /* Precondition: as src[0] is non-empty and the inputs are ordered
1539 * by size, all src[i > 0] are non-empty too. */
1540 while (zuiNext(&src
[0],&zval
)) {
1541 double score
, value
;
1543 score
= src
[0].weight
* zval
.score
;
1544 for (j
= 1; j
< setnum
; j
++) {
1545 /* It is not safe to access the zset we are
1546 * iterating, so explicitly check for equal object. */
1547 if (src
[j
].subject
== src
[0].subject
) {
1548 value
= zval
.score
*src
[j
].weight
;
1549 zunionInterAggregate(&score
,value
,aggregate
);
1550 } else if (zuiFind(&src
[j
],&zval
,&value
)) {
1551 value
*= src
[j
].weight
;
1552 zunionInterAggregate(&score
,value
,aggregate
);
1558 /* Only continue when present in every input. */
1560 tmp
= zuiObjectFromValue(&zval
);
1561 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1562 incrRefCount(tmp
); /* added to skiplist */
1563 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1564 incrRefCount(tmp
); /* added to dictionary */
1566 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1567 if (sdslen(tmp
->ptr
) > maxelelen
)
1568 maxelelen
= sdslen(tmp
->ptr
);
1572 } else if (op
== REDIS_OP_UNION
) {
1573 for (i
= 0; i
< setnum
; i
++) {
1574 if (zuiLength(&src
[i
]) == 0)
1577 while (zuiNext(&src
[i
],&zval
)) {
1578 double score
, value
;
1580 /* Skip key when already processed */
1581 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1584 /* Initialize score */
1585 score
= src
[i
].weight
* zval
.score
;
1587 /* Because the inputs are sorted by size, it's only possible
1588 * for sets at larger indices to hold this element. */
1589 for (j
= (i
+1); j
< setnum
; j
++) {
1590 /* It is not safe to access the zset we are
1591 * iterating, so explicitly check for equal object. */
1592 if(src
[j
].subject
== src
[i
].subject
) {
1593 value
= zval
.score
*src
[j
].weight
;
1594 zunionInterAggregate(&score
,value
,aggregate
);
1595 } else if (zuiFind(&src
[j
],&zval
,&value
)) {
1596 value
*= src
[j
].weight
;
1597 zunionInterAggregate(&score
,value
,aggregate
);
1601 tmp
= zuiObjectFromValue(&zval
);
1602 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1603 incrRefCount(zval
.ele
); /* added to skiplist */
1604 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1605 incrRefCount(zval
.ele
); /* added to dictionary */
1607 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1608 if (sdslen(tmp
->ptr
) > maxelelen
)
1609 maxelelen
= sdslen(tmp
->ptr
);
1613 redisPanic("Unknown operator");
1616 for (i
= 0; i
< setnum
; i
++)
1617 zuiClearIterator(&src
[i
]);
1619 if (dbDelete(c
->db
,dstkey
)) {
1620 signalModifiedKey(c
->db
,dstkey
);
1624 if (dstzset
->zsl
->length
) {
1625 /* Convert to ziplist when in limits. */
1626 if (dstzset
->zsl
->length
<= server
.zset_max_ziplist_entries
&&
1627 maxelelen
<= server
.zset_max_ziplist_value
)
1628 zsetConvert(dstobj
,REDIS_ENCODING_ZIPLIST
);
1630 dbAdd(c
->db
,dstkey
,dstobj
);
1631 addReplyLongLong(c
,zsetLength(dstobj
));
1632 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1635 decrRefCount(dstobj
);
1636 addReply(c
,shared
.czero
);
1641 void zunionstoreCommand(redisClient
*c
) {
1642 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1645 void zinterstoreCommand(redisClient
*c
) {
1646 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1649 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1650 robj
*key
= c
->argv
[1];
1658 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1659 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1661 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1663 } else if (c
->argc
>= 5) {
1664 addReply(c
,shared
.syntaxerr
);
1668 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1669 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1671 /* Sanitize indexes. */
1672 llen
= zsetLength(zobj
);
1673 if (start
< 0) start
= llen
+start
;
1674 if (end
< 0) end
= llen
+end
;
1675 if (start
< 0) start
= 0;
1677 /* Invariant: start >= 0, so this test will be true when end < 0.
1678 * The range is empty when start > end or start >= length. */
1679 if (start
> end
|| start
>= llen
) {
1680 addReply(c
,shared
.emptymultibulk
);
1683 if (end
>= llen
) end
= llen
-1;
1684 rangelen
= (end
-start
)+1;
1686 /* Return the result in form of a multi-bulk reply */
1687 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1689 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1690 unsigned char *zl
= zobj
->ptr
;
1691 unsigned char *eptr
, *sptr
;
1692 unsigned char *vstr
;
1697 eptr
= ziplistIndex(zl
,-2-(2*start
));
1699 eptr
= ziplistIndex(zl
,2*start
);
1701 redisAssertWithInfo(c
,zobj
,eptr
!= NULL
);
1702 sptr
= ziplistNext(zl
,eptr
);
1704 while (rangelen
--) {
1705 redisAssertWithInfo(c
,zobj
,eptr
!= NULL
&& sptr
!= NULL
);
1706 redisAssertWithInfo(c
,zobj
,ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1708 addReplyBulkLongLong(c
,vlong
);
1710 addReplyBulkCBuffer(c
,vstr
,vlen
);
1713 addReplyDouble(c
,zzlGetScore(sptr
));
1716 zzlPrev(zl
,&eptr
,&sptr
);
1718 zzlNext(zl
,&eptr
,&sptr
);
1721 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1722 zset
*zs
= zobj
->ptr
;
1723 zskiplist
*zsl
= zs
->zsl
;
1727 /* Check if starting point is trivial, before doing log(N) lookup. */
1731 ln
= zslGetElementByRank(zsl
,llen
-start
);
1733 ln
= zsl
->header
->level
[0].forward
;
1735 ln
= zslGetElementByRank(zsl
,start
+1);
1739 redisAssertWithInfo(c
,zobj
,ln
!= NULL
);
1741 addReplyBulk(c
,ele
);
1743 addReplyDouble(c
,ln
->score
);
1744 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1747 redisPanic("Unknown sorted set encoding");
1751 void zrangeCommand(redisClient
*c
) {
1752 zrangeGenericCommand(c
,0);
1755 void zrevrangeCommand(redisClient
*c
) {
1756 zrangeGenericCommand(c
,1);
1759 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */
1760 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
) {
1762 robj
*key
= c
->argv
[1];
1764 int offset
= 0, limit
= -1;
1766 unsigned long rangelen
= 0;
1767 void *replylen
= NULL
;
1770 /* Parse the range arguments. */
1772 /* Range is given as [max,min] */
1773 maxidx
= 2; minidx
= 3;
1775 /* Range is given as [min,max] */
1776 minidx
= 2; maxidx
= 3;
1779 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1780 addReplyError(c
,"min or max is not a double");
1784 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1785 * 4 arguments, so we'll never enter the following code path. */
1787 int remaining
= c
->argc
- 4;
1791 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1794 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1795 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1796 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1797 pos
+= 3; remaining
-= 3;
1799 addReply(c
,shared
.syntaxerr
);
1805 /* Ok, lookup the key and get the range */
1806 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
||
1807 checkType(c
,zobj
,REDIS_ZSET
)) return;
1809 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1810 unsigned char *zl
= zobj
->ptr
;
1811 unsigned char *eptr
, *sptr
;
1812 unsigned char *vstr
;
1817 /* If reversed, get the last node in range as starting point. */
1819 eptr
= zzlLastInRange(zl
,range
);
1821 eptr
= zzlFirstInRange(zl
,range
);
1824 /* No "first" element in the specified interval. */
1826 addReply(c
, shared
.emptymultibulk
);
1830 /* Get score pointer for the first element. */
1831 redisAssertWithInfo(c
,zobj
,eptr
!= NULL
);
1832 sptr
= ziplistNext(zl
,eptr
);
1834 /* We don't know in advance how many matching elements there are in the
1835 * list, so we push this object that will represent the multi-bulk
1836 * length in the output buffer, and will "fix" it later */
1837 replylen
= addDeferredMultiBulkLength(c
);
1839 /* If there is an offset, just traverse the number of elements without
1840 * checking the score because that is done in the next loop. */
1841 while (eptr
&& offset
--) {
1843 zzlPrev(zl
,&eptr
,&sptr
);
1845 zzlNext(zl
,&eptr
,&sptr
);
1849 while (eptr
&& limit
--) {
1850 score
= zzlGetScore(sptr
);
1852 /* Abort when the node is no longer in range. */
1854 if (!zslValueGteMin(score
,&range
)) break;
1856 if (!zslValueLteMax(score
,&range
)) break;
1859 /* We know the element exists, so ziplistGet should always succeed */
1860 redisAssertWithInfo(c
,zobj
,ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1864 addReplyBulkLongLong(c
,vlong
);
1866 addReplyBulkCBuffer(c
,vstr
,vlen
);
1870 addReplyDouble(c
,score
);
1873 /* Move to next node */
1875 zzlPrev(zl
,&eptr
,&sptr
);
1877 zzlNext(zl
,&eptr
,&sptr
);
1880 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1881 zset
*zs
= zobj
->ptr
;
1882 zskiplist
*zsl
= zs
->zsl
;
1885 /* If reversed, get the last node in range as starting point. */
1887 ln
= zslLastInRange(zsl
,range
);
1889 ln
= zslFirstInRange(zsl
,range
);
1892 /* No "first" element in the specified interval. */
1894 addReply(c
, shared
.emptymultibulk
);
1898 /* We don't know in advance how many matching elements there are in the
1899 * list, so we push this object that will represent the multi-bulk
1900 * length in the output buffer, and will "fix" it later */
1901 replylen
= addDeferredMultiBulkLength(c
);
1903 /* If there is an offset, just traverse the number of elements without
1904 * checking the score because that is done in the next loop. */
1905 while (ln
&& offset
--) {
1909 ln
= ln
->level
[0].forward
;
1913 while (ln
&& limit
--) {
1914 /* Abort when the node is no longer in range. */
1916 if (!zslValueGteMin(ln
->score
,&range
)) break;
1918 if (!zslValueLteMax(ln
->score
,&range
)) break;
1922 addReplyBulk(c
,ln
->obj
);
1925 addReplyDouble(c
,ln
->score
);
1928 /* Move to next node */
1932 ln
= ln
->level
[0].forward
;
1936 redisPanic("Unknown sorted set encoding");
1943 setDeferredMultiBulkLength(c
, replylen
, rangelen
);
1946 void zrangebyscoreCommand(redisClient
*c
) {
1947 genericZrangebyscoreCommand(c
,0);
1950 void zrevrangebyscoreCommand(redisClient
*c
) {
1951 genericZrangebyscoreCommand(c
,1);
1954 void zcountCommand(redisClient
*c
) {
1955 robj
*key
= c
->argv
[1];
1960 /* Parse the range arguments */
1961 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1962 addReplyError(c
,"min or max is not a double");
1966 /* Lookup the sorted set */
1967 if ((zobj
= lookupKeyReadOrReply(c
, key
, shared
.czero
)) == NULL
||
1968 checkType(c
, zobj
, REDIS_ZSET
)) return;
1970 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1971 unsigned char *zl
= zobj
->ptr
;
1972 unsigned char *eptr
, *sptr
;
1975 /* Use the first element in range as the starting point */
1976 eptr
= zzlFirstInRange(zl
,range
);
1978 /* No "first" element */
1980 addReply(c
, shared
.czero
);
1984 /* First element is in range */
1985 sptr
= ziplistNext(zl
,eptr
);
1986 score
= zzlGetScore(sptr
);
1987 redisAssertWithInfo(c
,zobj
,zslValueLteMax(score
,&range
));
1989 /* Iterate over elements in range */
1991 score
= zzlGetScore(sptr
);
1993 /* Abort when the node is no longer in range. */
1994 if (!zslValueLteMax(score
,&range
)) {
1998 zzlNext(zl
,&eptr
,&sptr
);
2001 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
2002 zset
*zs
= zobj
->ptr
;
2003 zskiplist
*zsl
= zs
->zsl
;
2007 /* Find first element in range */
2008 zn
= zslFirstInRange(zsl
, range
);
2010 /* Use rank of first element, if any, to determine preliminary count */
2012 rank
= zslGetRank(zsl
, zn
->score
, zn
->obj
);
2013 count
= (zsl
->length
- (rank
- 1));
2015 /* Find last element in range */
2016 zn
= zslLastInRange(zsl
, range
);
2018 /* Use rank of last element, if any, to determine the actual count */
2020 rank
= zslGetRank(zsl
, zn
->score
, zn
->obj
);
2021 count
-= (zsl
->length
- rank
);
2025 redisPanic("Unknown sorted set encoding");
2028 addReplyLongLong(c
, count
);
2031 void zcardCommand(redisClient
*c
) {
2032 robj
*key
= c
->argv
[1];
2035 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
2036 checkType(c
,zobj
,REDIS_ZSET
)) return;
2038 addReplyLongLong(c
,zsetLength(zobj
));
2041 void zscoreCommand(redisClient
*c
) {
2042 robj
*key
= c
->argv
[1];
2046 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
2047 checkType(c
,zobj
,REDIS_ZSET
)) return;
2049 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
2050 if (zzlFind(zobj
->ptr
,c
->argv
[2],&score
) != NULL
)
2051 addReplyDouble(c
,score
);
2053 addReply(c
,shared
.nullbulk
);
2054 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
2055 zset
*zs
= zobj
->ptr
;
2058 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2059 de
= dictFind(zs
->dict
,c
->argv
[2]);
2061 score
= *(double*)dictGetEntryVal(de
);
2062 addReplyDouble(c
,score
);
2064 addReply(c
,shared
.nullbulk
);
2067 redisPanic("Unknown sorted set encoding");
2071 void zrankGenericCommand(redisClient
*c
, int reverse
) {
2072 robj
*key
= c
->argv
[1];
2073 robj
*ele
= c
->argv
[2];
2078 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
2079 checkType(c
,zobj
,REDIS_ZSET
)) return;
2080 llen
= zsetLength(zobj
);
2082 redisAssertWithInfo(c
,ele
,ele
->encoding
== REDIS_ENCODING_RAW
);
2083 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
2084 unsigned char *zl
= zobj
->ptr
;
2085 unsigned char *eptr
, *sptr
;
2087 eptr
= ziplistIndex(zl
,0);
2088 redisAssertWithInfo(c
,zobj
,eptr
!= NULL
);
2089 sptr
= ziplistNext(zl
,eptr
);
2090 redisAssertWithInfo(c
,zobj
,sptr
!= NULL
);
2093 while(eptr
!= NULL
) {
2094 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
2097 zzlNext(zl
,&eptr
,&sptr
);
2102 addReplyLongLong(c
,llen
-rank
);
2104 addReplyLongLong(c
,rank
-1);
2106 addReply(c
,shared
.nullbulk
);
2108 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
2109 zset
*zs
= zobj
->ptr
;
2110 zskiplist
*zsl
= zs
->zsl
;
2114 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2115 de
= dictFind(zs
->dict
,ele
);
2117 score
= *(double*)dictGetEntryVal(de
);
2118 rank
= zslGetRank(zsl
,score
,ele
);
2119 redisAssertWithInfo(c
,ele
,rank
); /* Existing elements always have a rank. */
2121 addReplyLongLong(c
,llen
-rank
);
2123 addReplyLongLong(c
,rank
-1);
2125 addReply(c
,shared
.nullbulk
);
2128 redisPanic("Unknown sorted set encoding");
2132 void zrankCommand(redisClient
*c
) {
2133 zrankGenericCommand(c
, 0);
2136 void zrevrankCommand(redisClient
*c
) {
2137 zrankGenericCommand(c
, 1);