]>
git.saurik.com Git - redis.git/blob - src/t_zset.c
5 /*-----------------------------------------------------------------------------
7 *----------------------------------------------------------------------------*/
9 /* ZSETs are ordered sets using two data structures to hold the same elements
10 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
13 * The elements are added to an hash table mapping Redis objects to scores.
14 * At the same time the elements are added to a skip list mapping scores
15 * to Redis objects (so objects are sorted by scores in this "view"). */
17 /* This skiplist implementation is almost a C translation of the original
18 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
19 * Alternative to Balanced Trees", modified in three ways:
20 * a) this implementation allows for repeated values.
21 * b) the comparison is not just by key (our 'score') but by satellite data.
22 * c) there is a back pointer, so it's a doubly linked list with the back
23 * pointers being only at "level 1". This allows to traverse the list
24 * from tail to head, useful for ZREVRANGE. */
26 zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
27 zskiplistNode
*zn
= zmalloc(sizeof(*zn
)+level
*sizeof(struct zskiplistLevel
));
33 zskiplist
*zslCreate(void) {
37 zsl
= zmalloc(sizeof(*zsl
));
40 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
41 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
42 zsl
->header
->level
[j
].forward
= NULL
;
43 zsl
->header
->level
[j
].span
= 0;
45 zsl
->header
->backward
= NULL
;
50 void zslFreeNode(zskiplistNode
*node
) {
51 decrRefCount(node
->obj
);
55 void zslFree(zskiplist
*zsl
) {
56 zskiplistNode
*node
= zsl
->header
->level
[0].forward
, *next
;
60 next
= node
->level
[0].forward
;
67 int zslRandomLevel(void) {
69 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
71 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
74 zskiplistNode
*zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
75 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
76 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
80 for (i
= zsl
->level
-1; i
>= 0; i
--) {
81 /* store rank that is crossed to reach the insert position */
82 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
83 while (x
->level
[i
].forward
&&
84 (x
->level
[i
].forward
->score
< score
||
85 (x
->level
[i
].forward
->score
== score
&&
86 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0))) {
87 rank
[i
] += x
->level
[i
].span
;
88 x
= x
->level
[i
].forward
;
92 /* we assume the key is not already inside, since we allow duplicated
93 * scores, and the re-insertion of score and redis object should never
94 * happpen since the caller of zslInsert() should test in the hash table
95 * if the element is already inside or not. */
96 level
= zslRandomLevel();
97 if (level
> zsl
->level
) {
98 for (i
= zsl
->level
; i
< level
; i
++) {
100 update
[i
] = zsl
->header
;
101 update
[i
]->level
[i
].span
= zsl
->length
;
105 x
= zslCreateNode(level
,score
,obj
);
106 for (i
= 0; i
< level
; i
++) {
107 x
->level
[i
].forward
= update
[i
]->level
[i
].forward
;
108 update
[i
]->level
[i
].forward
= x
;
110 /* update span covered by update[i] as x is inserted here */
111 x
->level
[i
].span
= update
[i
]->level
[i
].span
- (rank
[0] - rank
[i
]);
112 update
[i
]->level
[i
].span
= (rank
[0] - rank
[i
]) + 1;
115 /* increment span for untouched levels */
116 for (i
= level
; i
< zsl
->level
; i
++) {
117 update
[i
]->level
[i
].span
++;
120 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
121 if (x
->level
[0].forward
)
122 x
->level
[0].forward
->backward
= x
;
129 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
130 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
132 for (i
= 0; i
< zsl
->level
; i
++) {
133 if (update
[i
]->level
[i
].forward
== x
) {
134 update
[i
]->level
[i
].span
+= x
->level
[i
].span
- 1;
135 update
[i
]->level
[i
].forward
= x
->level
[i
].forward
;
137 update
[i
]->level
[i
].span
-= 1;
140 if (x
->level
[0].forward
) {
141 x
->level
[0].forward
->backward
= x
->backward
;
143 zsl
->tail
= x
->backward
;
145 while(zsl
->level
> 1 && zsl
->header
->level
[zsl
->level
-1].forward
== NULL
)
150 /* Delete an element with matching score/object from the skiplist. */
151 int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
152 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
156 for (i
= zsl
->level
-1; i
>= 0; i
--) {
157 while (x
->level
[i
].forward
&&
158 (x
->level
[i
].forward
->score
< score
||
159 (x
->level
[i
].forward
->score
== score
&&
160 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0)))
161 x
= x
->level
[i
].forward
;
164 /* We may have multiple elements with the same score, what we need
165 * is to find the element with both the right score and object. */
166 x
= x
->level
[0].forward
;
167 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
168 zslDeleteNode(zsl
, x
, update
);
172 return 0; /* not found */
174 return 0; /* not found */
177 /* Struct to hold a inclusive/exclusive range spec. */
180 int minex
, maxex
; /* are min or max exclusive? */
183 static int zslValueGteMin(double value
, zrangespec
*spec
) {
184 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
187 static int zslValueLteMax(double value
, zrangespec
*spec
) {
188 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
191 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 /* The tail is in range, so the previous block should always return a
230 * node that is non-NULL and the last one to be out of range. */
231 x
= x
->level
[0].forward
;
232 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
236 /* Find the last node that is contained in the specified range.
237 * Returns NULL when no element is contained in the range. */
238 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
242 /* If everything is out of range, return early. */
243 if (!zslIsInRange(zsl
,&range
)) return NULL
;
246 for (i
= zsl
->level
-1; i
>= 0; i
--) {
247 /* Go forward while *IN* range. */
248 while (x
->level
[i
].forward
&&
249 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
250 x
= x
->level
[i
].forward
;
253 /* The header is in range, so the previous block should always return a
254 * node that is non-NULL and in range. */
255 redisAssert(x
!= NULL
&& zslValueInRange(x
->score
,&range
));
259 /* Delete all the elements with score between min and max from the skiplist.
260 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
261 * Note that this function takes the reference to the hash table view of the
262 * sorted set, in order to remove the elements from the hash table too. */
263 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
264 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
265 unsigned long removed
= 0;
269 for (i
= zsl
->level
-1; i
>= 0; i
--) {
270 while (x
->level
[i
].forward
&& (range
.minex
?
271 x
->level
[i
].forward
->score
<= range
.min
:
272 x
->level
[i
].forward
->score
< range
.min
))
273 x
= x
->level
[i
].forward
;
277 /* Current node is the last with score < or <= min. */
278 x
= x
->level
[0].forward
;
280 /* Delete nodes while in range. */
281 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
282 zskiplistNode
*next
= x
->level
[0].forward
;
283 zslDeleteNode(zsl
,x
,update
);
284 dictDelete(dict
,x
->obj
);
292 /* Delete all the elements with rank between start and end from the skiplist.
293 * Start and end are inclusive. Note that start and end need to be 1-based */
294 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
295 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
296 unsigned long traversed
= 0, removed
= 0;
300 for (i
= zsl
->level
-1; i
>= 0; i
--) {
301 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
302 traversed
+= x
->level
[i
].span
;
303 x
= x
->level
[i
].forward
;
309 x
= x
->level
[0].forward
;
310 while (x
&& traversed
<= end
) {
311 zskiplistNode
*next
= x
->level
[0].forward
;
312 zslDeleteNode(zsl
,x
,update
);
313 dictDelete(dict
,x
->obj
);
322 /* Find the rank for an element by both score and key.
323 * Returns 0 when the element cannot be found, rank otherwise.
324 * Note that the rank is 1-based due to the span of zsl->header to the
326 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
328 unsigned long rank
= 0;
332 for (i
= zsl
->level
-1; i
>= 0; i
--) {
333 while (x
->level
[i
].forward
&&
334 (x
->level
[i
].forward
->score
< score
||
335 (x
->level
[i
].forward
->score
== score
&&
336 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
337 rank
+= x
->level
[i
].span
;
338 x
= x
->level
[i
].forward
;
341 /* x might be equal to zsl->header, so test if obj is non-NULL */
342 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
349 /* Finds an element by its rank. The rank argument needs to be 1-based. */
350 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
352 unsigned long traversed
= 0;
356 for (i
= zsl
->level
-1; i
>= 0; i
--) {
357 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
359 traversed
+= x
->level
[i
].span
;
360 x
= x
->level
[i
].forward
;
362 if (traversed
== rank
) {
369 /* Populate the rangespec according to the objects min and max. */
370 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
372 spec
->minex
= spec
->maxex
= 0;
374 /* Parse the min-max interval. If one of the values is prefixed
375 * by the "(" character, it's considered "open". For instance
376 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
377 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
378 if (min
->encoding
== REDIS_ENCODING_INT
) {
379 spec
->min
= (long)min
->ptr
;
381 if (((char*)min
->ptr
)[0] == '(') {
382 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
383 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
386 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
387 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
390 if (max
->encoding
== REDIS_ENCODING_INT
) {
391 spec
->max
= (long)max
->ptr
;
393 if (((char*)max
->ptr
)[0] == '(') {
394 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
395 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
398 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
399 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
406 /*-----------------------------------------------------------------------------
407 * Ziplist-backed sorted set API
408 *----------------------------------------------------------------------------*/
410 double zzlGetScore(unsigned char *sptr
) {
417 redisAssert(sptr
!= NULL
);
418 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
421 memcpy(buf
,vstr
,vlen
);
423 score
= strtod(buf
,NULL
);
431 /* Compare element in sorted set with given element. */
432 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
436 unsigned char vbuf
[32];
439 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
441 /* Store string representation of long long in buf. */
442 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
446 minlen
= (vlen
< clen
) ? vlen
: clen
;
447 cmp
= memcmp(vstr
,cstr
,minlen
);
448 if (cmp
== 0) return vlen
-clen
;
452 unsigned int zzlLength(unsigned char *zl
) {
453 return ziplistLen(zl
)/2;
456 /* Move to next entry based on the values in eptr and sptr. Both are set to
457 * NULL when there is no next entry. */
458 void zzlNext(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
459 unsigned char *_eptr
, *_sptr
;
460 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
462 _eptr
= ziplistNext(zl
,*sptr
);
464 _sptr
= ziplistNext(zl
,_eptr
);
465 redisAssert(_sptr
!= NULL
);
475 /* Move to the previous entry based on the values in eptr and sptr. Both are
476 * set to NULL when there is no next entry. */
477 void zzlPrev(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
478 unsigned char *_eptr
, *_sptr
;
479 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
481 _sptr
= ziplistPrev(zl
,*eptr
);
483 _eptr
= ziplistPrev(zl
,_sptr
);
484 redisAssert(_eptr
!= NULL
);
486 /* No previous entry. */
494 /* Returns if there is a part of the zset is in range. Should only be used
495 * internally by zzlFirstInRange and zzlLastInRange. */
496 int zzlIsInRange(unsigned char *zl
, zrangespec
*range
) {
500 /* Test for ranges that will always be empty. */
501 if (range
->min
> range
->max
||
502 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
505 p
= ziplistIndex(zl
,-1); /* Last score. */
506 redisAssert(p
!= NULL
);
507 score
= zzlGetScore(p
);
508 if (!zslValueGteMin(score
,range
))
511 p
= ziplistIndex(zl
,1); /* First score. */
512 redisAssert(p
!= NULL
);
513 score
= zzlGetScore(p
);
514 if (!zslValueLteMax(score
,range
))
520 /* Find pointer to the first element contained in the specified range.
521 * Returns NULL when no element is contained in the range. */
522 unsigned char *zzlFirstInRange(robj
*zobj
, zrangespec range
) {
523 unsigned char *zl
= zobj
->ptr
;
524 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
527 /* If everything is out of range, return early. */
528 if (!zzlIsInRange(zl
,&range
)) return NULL
;
530 while (eptr
!= NULL
) {
531 sptr
= ziplistNext(zl
,eptr
);
532 redisAssert(sptr
!= NULL
);
534 score
= zzlGetScore(sptr
);
535 if (zslValueGteMin(score
,&range
))
538 /* Move to next element. */
539 eptr
= ziplistNext(zl
,sptr
);
545 /* Find pointer to the last element contained in the specified range.
546 * Returns NULL when no element is contained in the range. */
547 unsigned char *zzlLastInRange(robj
*zobj
, zrangespec range
) {
548 unsigned char *zl
= zobj
->ptr
;
549 unsigned char *eptr
= ziplistIndex(zl
,-2), *sptr
;
552 /* If everything is out of range, return early. */
553 if (!zzlIsInRange(zl
,&range
)) return NULL
;
555 while (eptr
!= NULL
) {
556 sptr
= ziplistNext(zl
,eptr
);
557 redisAssert(sptr
!= NULL
);
559 score
= zzlGetScore(sptr
);
560 if (zslValueLteMax(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(robj
*zobj
, robj
*ele
, double *score
) {
576 unsigned char *zl
= zobj
->ptr
;
577 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
579 ele
= getDecodedObject(ele
);
580 while (eptr
!= NULL
) {
581 sptr
= ziplistNext(zl
,eptr
);
582 redisAssert(sptr
!= NULL
);
584 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
585 /* Matching element, pull out score. */
586 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
591 /* Move to next element. */
592 eptr
= ziplistNext(zl
,sptr
);
599 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
600 * don't want to modify the one given as argument. */
601 int zzlDelete(robj
*zobj
, unsigned char *eptr
) {
602 unsigned char *zl
= zobj
->ptr
;
603 unsigned char *p
= eptr
;
605 /* TODO: add function to ziplist API to delete N elements from offset. */
606 zl
= ziplistDelete(zl
,&p
);
607 zl
= ziplistDelete(zl
,&p
);
612 int zzlInsertAt(robj
*zobj
, robj
*ele
, double score
, unsigned char *eptr
) {
613 unsigned char *zl
= zobj
->ptr
;
619 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
620 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
622 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
623 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
625 /* Keep offset relative to zl, as it might be re-allocated. */
627 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
630 /* Insert score after the element. */
631 redisAssert((sptr
= ziplistNext(zl
,eptr
)) != NULL
);
632 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
639 /* Insert (element,score) pair in ziplist. This function assumes the element is
640 * not yet present in the list. */
641 int zzlInsert(robj
*zobj
, robj
*ele
, double score
) {
642 unsigned char *zl
= zobj
->ptr
;
643 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
646 ele
= getDecodedObject(ele
);
647 while (eptr
!= NULL
) {
648 sptr
= ziplistNext(zl
,eptr
);
649 redisAssert(sptr
!= NULL
);
650 s
= zzlGetScore(sptr
);
653 /* First element with score larger than score for element to be
654 * inserted. This means we should take its spot in the list to
655 * maintain ordering. */
656 zzlInsertAt(zobj
,ele
,score
,eptr
);
658 } else if (s
== score
) {
659 /* Ensure lexicographical ordering for elements. */
660 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) > 0) {
661 zzlInsertAt(zobj
,ele
,score
,eptr
);
666 /* Move to next element. */
667 eptr
= ziplistNext(zl
,sptr
);
670 /* Push on tail of list when it was not yet inserted. */
672 zzlInsertAt(zobj
,ele
,score
,NULL
);
678 unsigned long zzlDeleteRangeByScore(robj
*zobj
, zrangespec range
) {
679 unsigned char *zl
= zobj
->ptr
;
680 unsigned char *eptr
, *sptr
;
682 unsigned long deleted
= 0;
684 eptr
= zzlFirstInRange(zobj
,range
);
685 if (eptr
== NULL
) return deleted
;
688 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
689 * byte and ziplistNext will return NULL. */
690 while ((sptr
= ziplistNext(zl
,eptr
)) != NULL
) {
691 score
= zzlGetScore(sptr
);
692 if (zslValueLteMax(score
,&range
)) {
693 /* Delete both the element and the score. */
694 zl
= ziplistDelete(zl
,&eptr
);
695 zl
= ziplistDelete(zl
,&eptr
);
698 /* No longer in range. */
706 /* Delete all the elements with rank between start and end from the skiplist.
707 * Start and end are inclusive. Note that start and end need to be 1-based */
708 unsigned long zzlDeleteRangeByRank(robj
*zobj
, unsigned int start
, unsigned int end
) {
709 unsigned int num
= (end
-start
)+1;
710 zobj
->ptr
= ziplistDeleteRange(zobj
->ptr
,2*(start
-1),2*num
);
714 /*-----------------------------------------------------------------------------
715 * Common sorted set API
716 *----------------------------------------------------------------------------*/
718 int zsLength(robj
*zobj
) {
720 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
721 length
= zzlLength(zobj
->ptr
);
722 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
723 length
= ((zset
*)zobj
->ptr
)->zsl
->length
;
725 redisPanic("Unknown sorted set encoding");
730 void zsConvert(robj
*zobj
, int encoding
) {
732 zskiplistNode
*node
, *next
;
736 if (zobj
->encoding
== encoding
) return;
737 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
738 unsigned char *zl
= zobj
->ptr
;
739 unsigned char *eptr
, *sptr
;
744 if (encoding
!= REDIS_ENCODING_RAW
)
745 redisPanic("Unknown target encoding");
747 zs
= zmalloc(sizeof(*zs
));
748 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
749 zs
->zsl
= zslCreate();
751 eptr
= ziplistIndex(zl
,0);
752 redisAssert(eptr
!= NULL
);
753 sptr
= ziplistNext(zl
,eptr
);
754 redisAssert(sptr
!= NULL
);
756 while (eptr
!= NULL
) {
757 score
= zzlGetScore(sptr
);
758 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
760 ele
= createStringObjectFromLongLong(vlong
);
762 ele
= createStringObject((char*)vstr
,vlen
);
764 /* Has incremented refcount since it was just created. */
765 node
= zslInsert(zs
->zsl
,score
,ele
);
766 redisAssert(dictAdd(zs
->dict
,ele
,&node
->score
) == DICT_OK
);
767 incrRefCount(ele
); /* Added to dictionary. */
768 zzlNext(zl
,&eptr
,&sptr
);
773 zobj
->encoding
= REDIS_ENCODING_RAW
;
774 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
775 unsigned char *zl
= ziplistNew();
777 if (encoding
!= REDIS_ENCODING_ZIPLIST
)
778 redisPanic("Unknown target encoding");
780 /* Approach similar to zslFree(), since we want to free the skiplist at
781 * the same time as creating the ziplist. */
783 dictRelease(zs
->dict
);
784 node
= zs
->zsl
->header
->level
[0].forward
;
785 zfree(zs
->zsl
->header
);
788 /* Immediately store pointer to ziplist in object because it will
789 * change because of reallocations when pushing to the ziplist. */
793 ele
= getDecodedObject(node
->obj
);
794 redisAssert(zzlInsertAt(zobj
,ele
,node
->score
,NULL
) == REDIS_OK
);
797 next
= node
->level
[0].forward
;
803 zobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
805 redisPanic("Unknown sorted set encoding");
809 /*-----------------------------------------------------------------------------
810 * Sorted set commands
811 *----------------------------------------------------------------------------*/
813 /* This generic command implements both ZADD and ZINCRBY. */
814 void zaddGenericCommand(redisClient
*c
, int incr
) {
815 static char *nanerr
= "resulting score is not a number (NaN)";
816 robj
*key
= c
->argv
[1];
820 double score
, curscore
= 0.0;
822 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&score
,NULL
) != REDIS_OK
)
825 zobj
= lookupKeyWrite(c
->db
,key
);
827 if (server
.zset_max_ziplist_entries
== 0 ||
828 server
.zset_max_ziplist_value
< sdslen(c
->argv
[3]->ptr
))
830 zobj
= createZsetObject();
832 zobj
= createZsetZiplistObject();
834 dbAdd(c
->db
,key
,zobj
);
836 if (zobj
->type
!= REDIS_ZSET
) {
837 addReply(c
,shared
.wrongtypeerr
);
842 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
845 /* Prefer non-encoded element when dealing with ziplists. */
847 if ((eptr
= zzlFind(zobj
,ele
,&curscore
)) != NULL
) {
851 addReplyError(c
,nanerr
);
852 /* Don't need to check if the sorted set is empty, because
853 * we know it has at least one element. */
858 /* Remove and re-insert when score changed. */
859 if (score
!= curscore
) {
860 redisAssert(zzlDelete(zobj
,eptr
) == REDIS_OK
);
861 redisAssert(zzlInsert(zobj
,ele
,score
) == REDIS_OK
);
863 signalModifiedKey(c
->db
,key
);
867 if (incr
) /* ZINCRBY */
868 addReplyDouble(c
,score
);
870 addReply(c
,shared
.czero
);
872 /* Optimize: check if the element is too large or the list becomes
873 * too long *before* executing zzlInsert. */
874 redisAssert(zzlInsert(zobj
,ele
,score
) == REDIS_OK
);
875 if (zzlLength(zobj
->ptr
) > server
.zset_max_ziplist_entries
)
876 zsConvert(zobj
,REDIS_ENCODING_RAW
);
877 if (sdslen(ele
->ptr
) > server
.zset_max_ziplist_value
)
878 zsConvert(zobj
,REDIS_ENCODING_RAW
);
880 signalModifiedKey(c
->db
,key
);
883 if (incr
) /* ZINCRBY */
884 addReplyDouble(c
,score
);
886 addReply(c
,shared
.cone
);
888 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
889 zset
*zs
= zobj
->ptr
;
890 zskiplistNode
*znode
;
893 ele
= c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
894 de
= dictFind(zs
->dict
,ele
);
896 curobj
= dictGetEntryKey(de
);
897 curscore
= *(double*)dictGetEntryVal(de
);
902 addReplyError(c
,nanerr
);
903 /* Don't need to check if the sorted set is empty, because
904 * we know it has at least one element. */
909 /* Remove and re-insert when score changed. We can safely delete
910 * the key object from the skiplist, since the dictionary still has
911 * a reference to it. */
912 if (score
!= curscore
) {
913 redisAssert(zslDelete(zs
->zsl
,curscore
,curobj
));
914 znode
= zslInsert(zs
->zsl
,score
,curobj
);
915 incrRefCount(curobj
); /* Re-inserted in skiplist. */
916 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
918 signalModifiedKey(c
->db
,key
);
922 if (incr
) /* ZINCRBY */
923 addReplyDouble(c
,score
);
925 addReply(c
,shared
.czero
);
927 znode
= zslInsert(zs
->zsl
,score
,ele
);
928 incrRefCount(ele
); /* Inserted in skiplist. */
929 redisAssert(dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
930 incrRefCount(ele
); /* Added to dictionary. */
932 signalModifiedKey(c
->db
,key
);
935 if (incr
) /* ZINCRBY */
936 addReplyDouble(c
,score
);
938 addReply(c
,shared
.cone
);
941 redisPanic("Unknown sorted set encoding");
945 void zaddCommand(redisClient
*c
) {
946 zaddGenericCommand(c
,0);
949 void zincrbyCommand(redisClient
*c
) {
950 zaddGenericCommand(c
,1);
953 void zremCommand(redisClient
*c
) {
954 robj
*key
= c
->argv
[1];
955 robj
*ele
= c
->argv
[2];
958 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
959 checkType(c
,zobj
,REDIS_ZSET
)) return;
961 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
964 if ((eptr
= zzlFind(zobj
,ele
,NULL
)) != NULL
) {
965 redisAssert(zzlDelete(zobj
,eptr
) == REDIS_OK
);
966 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
968 addReply(c
,shared
.czero
);
971 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
972 zset
*zs
= zobj
->ptr
;
976 de
= dictFind(zs
->dict
,ele
);
978 /* Delete from the skiplist */
979 score
= *(double*)dictGetEntryVal(de
);
980 redisAssert(zslDelete(zs
->zsl
,score
,ele
));
982 /* Delete from the hash table */
983 dictDelete(zs
->dict
,ele
);
984 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
985 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
987 addReply(c
,shared
.czero
);
991 redisPanic("Unknown sorted set encoding");
994 signalModifiedKey(c
->db
,key
);
996 addReply(c
,shared
.cone
);
999 void zremrangebyscoreCommand(redisClient
*c
) {
1000 robj
*key
= c
->argv
[1];
1003 unsigned long deleted
;
1005 /* Parse the range arguments. */
1006 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1007 addReplyError(c
,"min or max is not a double");
1011 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1012 checkType(c
,zobj
,REDIS_ZSET
)) return;
1014 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1015 deleted
= zzlDeleteRangeByScore(zobj
,range
);
1016 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1017 zset
*zs
= zobj
->ptr
;
1018 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1019 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1020 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1022 redisPanic("Unknown sorted set encoding");
1025 if (deleted
) signalModifiedKey(c
->db
,key
);
1026 server
.dirty
+= deleted
;
1027 addReplyLongLong(c
,deleted
);
1030 void zremrangebyrankCommand(redisClient
*c
) {
1031 robj
*key
= c
->argv
[1];
1036 unsigned long deleted
;
1038 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1039 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1041 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1042 checkType(c
,zobj
,REDIS_ZSET
)) return;
1044 /* Sanitize indexes. */
1045 llen
= zsLength(zobj
);
1046 if (start
< 0) start
= llen
+start
;
1047 if (end
< 0) end
= llen
+end
;
1048 if (start
< 0) start
= 0;
1050 /* Invariant: start >= 0, so this test will be true when end < 0.
1051 * The range is empty when start > end or start >= length. */
1052 if (start
> end
|| start
>= llen
) {
1053 addReply(c
,shared
.czero
);
1056 if (end
>= llen
) end
= llen
-1;
1058 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1059 /* Correct for 1-based rank. */
1060 deleted
= zzlDeleteRangeByRank(zobj
,start
+1,end
+1);
1061 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1062 zset
*zs
= zobj
->ptr
;
1064 /* Correct for 1-based rank. */
1065 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1066 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1067 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1069 redisPanic("Unknown sorted set encoding");
1072 if (deleted
) signalModifiedKey(c
->db
,key
);
1073 server
.dirty
+= deleted
;
1074 addReplyLongLong(c
,deleted
);
1079 int type
; /* Set, sorted set */
1084 /* Set iterators. */
1097 /* Sorted set iterators. */
1101 unsigned char *eptr
, *sptr
;
1105 zskiplistNode
*node
;
1112 /* Use dirty flags for pointers that need to be cleaned up in the next
1113 * iteration over the zsetopval. The dirty flag for the long long value is
1114 * special, since long long values don't need cleanup. Instead, it means that
1115 * we already checked that "ell" holds a long long, or tried to convert another
1116 * representation into a long long value. When this was successful,
1117 * OPVAL_VALID_LL is set as well. */
1118 #define OPVAL_DIRTY_ROBJ 1
1119 #define OPVAL_DIRTY_LL 2
1120 #define OPVAL_VALID_LL 4
1122 /* Store value retrieved from the iterator. */
1125 unsigned char _buf
[32]; /* Private buffer. */
1127 unsigned char *estr
;
1133 typedef union _iterset iterset
;
1134 typedef union _iterzset iterzset
;
1136 void zuiInitIterator(zsetopsrc
*op
) {
1137 if (op
->subject
== NULL
)
1140 if (op
->type
== REDIS_SET
) {
1141 iterset
*it
= &op
->iter
.set
;
1142 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1143 it
->is
.is
= op
->subject
->ptr
;
1145 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1146 it
->ht
.dict
= op
->subject
->ptr
;
1147 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1148 it
->ht
.de
= dictNext(it
->ht
.di
);
1150 redisPanic("Unknown set encoding");
1152 } else if (op
->type
== REDIS_ZSET
) {
1153 iterzset
*it
= &op
->iter
.zset
;
1154 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1155 it
->zl
.zl
= op
->subject
->ptr
;
1156 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1157 if (it
->zl
.eptr
!= NULL
) {
1158 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1159 redisAssert(it
->zl
.sptr
!= NULL
);
1161 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1162 it
->sl
.zs
= op
->subject
->ptr
;
1163 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1165 redisPanic("Unknown sorted set encoding");
1168 redisPanic("Unsupported type");
1172 void zuiClearIterator(zsetopsrc
*op
) {
1173 if (op
->subject
== NULL
)
1176 if (op
->type
== REDIS_SET
) {
1177 iterset
*it
= &op
->iter
.set
;
1178 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1179 REDIS_NOTUSED(it
); /* skip */
1180 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1181 dictReleaseIterator(it
->ht
.di
);
1183 redisPanic("Unknown set encoding");
1185 } else if (op
->type
== REDIS_ZSET
) {
1186 iterzset
*it
= &op
->iter
.zset
;
1187 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1188 REDIS_NOTUSED(it
); /* skip */
1189 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1190 REDIS_NOTUSED(it
); /* skip */
1192 redisPanic("Unknown sorted set encoding");
1195 redisPanic("Unsupported type");
1199 int zuiLength(zsetopsrc
*op
) {
1200 if (op
->subject
== NULL
)
1203 if (op
->type
== REDIS_SET
) {
1204 iterset
*it
= &op
->iter
.set
;
1205 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1206 return intsetLen(it
->is
.is
);
1207 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1208 return dictSize(it
->ht
.dict
);
1210 redisPanic("Unknown set encoding");
1212 } else if (op
->type
== REDIS_ZSET
) {
1213 iterzset
*it
= &op
->iter
.zset
;
1214 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1215 return zzlLength(it
->zl
.zl
);
1216 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1217 return it
->sl
.zs
->zsl
->length
;
1219 redisPanic("Unknown sorted set encoding");
1222 redisPanic("Unsupported type");
1226 /* Check if the current value is valid. If so, store it in the passed structure
1227 * and move to the next element. If not valid, this means we have reached the
1228 * end of the structure and can abort. */
1229 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1230 if (op
->subject
== NULL
)
1233 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1234 decrRefCount(val
->ele
);
1236 bzero(val
,sizeof(zsetopval
));
1238 if (op
->type
== REDIS_SET
) {
1239 iterset
*it
= &op
->iter
.set
;
1240 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1241 if (!intsetGet(it
->is
.is
,it
->is
.ii
,&val
->ell
))
1245 /* Move to next element. */
1247 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1248 if (it
->ht
.de
== NULL
)
1250 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1253 /* Move to next element. */
1254 it
->ht
.de
= dictNext(it
->ht
.di
);
1256 redisPanic("Unknown set encoding");
1258 } else if (op
->type
== REDIS_ZSET
) {
1259 iterzset
*it
= &op
->iter
.zset
;
1260 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1261 /* No need to check both, but better be explicit. */
1262 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1264 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1265 val
->score
= zzlGetScore(it
->zl
.sptr
);
1267 /* Move to next element. */
1268 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1269 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1270 if (it
->sl
.node
== NULL
)
1272 val
->ele
= it
->sl
.node
->obj
;
1273 val
->score
= it
->sl
.node
->score
;
1275 /* Move to next element. */
1276 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1278 redisPanic("Unknown sorted set encoding");
1281 redisPanic("Unsupported type");
1286 int zuiLongLongFromValue(zsetopval
*val
) {
1287 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1288 val
->flags
|= OPVAL_DIRTY_LL
;
1290 if (val
->ele
!= NULL
) {
1291 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1292 val
->ell
= (long)val
->ele
->ptr
;
1293 val
->flags
|= OPVAL_VALID_LL
;
1294 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1295 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1296 val
->flags
|= OPVAL_VALID_LL
;
1298 redisPanic("Unsupported element encoding");
1300 } else if (val
->estr
!= NULL
) {
1301 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1302 val
->flags
|= OPVAL_VALID_LL
;
1304 /* The long long was already set, flag as valid. */
1305 val
->flags
|= OPVAL_VALID_LL
;
1308 return val
->flags
& OPVAL_VALID_LL
;
1311 robj
*zuiObjectFromValue(zsetopval
*val
) {
1312 if (val
->ele
== NULL
) {
1313 if (val
->estr
!= NULL
) {
1314 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1316 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1318 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1323 int zuiBufferFromValue(zsetopval
*val
) {
1324 if (val
->estr
== NULL
) {
1325 if (val
->ele
!= NULL
) {
1326 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1327 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1328 val
->estr
= val
->_buf
;
1329 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1330 val
->elen
= sdslen(val
->ele
->ptr
);
1331 val
->estr
= val
->ele
->ptr
;
1333 redisPanic("Unsupported element encoding");
1336 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1337 val
->estr
= val
->_buf
;
1343 /* Find value pointed to by val in the source pointer to by op. When found,
1344 * return 1 and store its score in target. Return 0 otherwise. */
1345 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1346 if (op
->subject
== NULL
)
1349 if (op
->type
== REDIS_SET
) {
1350 iterset
*it
= &op
->iter
.set
;
1352 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1353 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1359 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1360 zuiObjectFromValue(val
);
1361 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1368 redisPanic("Unknown set encoding");
1370 } else if (op
->type
== REDIS_ZSET
) {
1371 iterzset
*it
= &op
->iter
.zset
;
1372 zuiObjectFromValue(val
);
1374 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1375 if (zzlFind(op
->subject
,val
->ele
,score
) != NULL
) {
1376 /* Score is already set by zzlFind. */
1381 } else if (op
->encoding
== REDIS_ENCODING_RAW
) {
1383 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1384 *score
= *(double*)dictGetEntryVal(de
);
1390 redisPanic("Unknown sorted set encoding");
1393 redisPanic("Unsupported type");
1397 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1398 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1401 #define REDIS_AGGR_SUM 1
1402 #define REDIS_AGGR_MIN 2
1403 #define REDIS_AGGR_MAX 3
1404 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1406 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1407 if (aggregate
== REDIS_AGGR_SUM
) {
1408 *target
= *target
+ val
;
1409 /* The result of adding two doubles is NaN when one variable
1410 * is +inf and the other is -inf. When these numbers are added,
1411 * we maintain the convention of the result being 0.0. */
1412 if (isnan(*target
)) *target
= 0.0;
1413 } else if (aggregate
== REDIS_AGGR_MIN
) {
1414 *target
= val
< *target
? val
: *target
;
1415 } else if (aggregate
== REDIS_AGGR_MAX
) {
1416 *target
= val
> *target
? val
: *target
;
1419 redisPanic("Unknown ZUNION/INTER aggregate type");
1423 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1425 int aggregate
= REDIS_AGGR_SUM
;
1431 zskiplistNode
*znode
;
1434 /* expect setnum input keys to be given */
1435 setnum
= atoi(c
->argv
[2]->ptr
);
1438 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1442 /* test if the expected number of keys would overflow */
1443 if (3+setnum
> c
->argc
) {
1444 addReply(c
,shared
.syntaxerr
);
1448 /* read keys to be used for input */
1449 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1450 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1451 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1453 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1455 addReply(c
,shared
.wrongtypeerr
);
1459 src
[i
].subject
= obj
;
1460 src
[i
].type
= obj
->type
;
1461 src
[i
].encoding
= obj
->encoding
;
1463 src
[i
].subject
= NULL
;
1466 /* Default all weights to 1. */
1467 src
[i
].weight
= 1.0;
1470 /* parse optional extra arguments */
1472 int remaining
= c
->argc
- j
;
1475 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1477 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1478 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1479 "weight value is not a double") != REDIS_OK
)
1485 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1487 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1488 aggregate
= REDIS_AGGR_SUM
;
1489 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1490 aggregate
= REDIS_AGGR_MIN
;
1491 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1492 aggregate
= REDIS_AGGR_MAX
;
1495 addReply(c
,shared
.syntaxerr
);
1501 addReply(c
,shared
.syntaxerr
);
1507 for (i
= 0; i
< setnum
; i
++)
1508 zuiInitIterator(&src
[i
]);
1510 /* sort sets from the smallest to largest, this will improve our
1511 * algorithm's performance */
1512 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1514 dstobj
= createZsetObject();
1515 dstzset
= dstobj
->ptr
;
1517 if (op
== REDIS_OP_INTER
) {
1518 /* Skip everything if the smallest input is empty. */
1519 if (zuiLength(&src
[0]) > 0) {
1520 /* Precondition: as src[0] is non-empty and the inputs are ordered
1521 * by size, all src[i > 0] are non-empty too. */
1522 while (zuiNext(&src
[0],&zval
)) {
1523 double score
, value
;
1525 score
= src
[0].weight
* zval
.score
;
1526 for (j
= 1; j
< setnum
; j
++) {
1527 if (zuiFind(&src
[j
],&zval
,&value
)) {
1528 value
*= src
[j
].weight
;
1529 zunionInterAggregate(&score
,value
,aggregate
);
1535 /* Only continue when present in every input. */
1537 tmp
= zuiObjectFromValue(&zval
);
1538 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1539 incrRefCount(tmp
); /* added to skiplist */
1540 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1541 incrRefCount(tmp
); /* added to dictionary */
1545 } else if (op
== REDIS_OP_UNION
) {
1546 for (i
= 0; i
< setnum
; i
++) {
1547 if (zuiLength(&src
[0]) == 0)
1550 while (zuiNext(&src
[i
],&zval
)) {
1551 double score
, value
;
1553 /* Skip key when already processed */
1554 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1557 /* Initialize score */
1558 score
= src
[i
].weight
* zval
.score
;
1560 /* Because the inputs are sorted by size, it's only possible
1561 * for sets at larger indices to hold this element. */
1562 for (j
= (i
+1); j
< setnum
; j
++) {
1563 if (zuiFind(&src
[j
],&zval
,&value
)) {
1564 value
*= src
[j
].weight
;
1565 zunionInterAggregate(&score
,value
,aggregate
);
1569 tmp
= zuiObjectFromValue(&zval
);
1570 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1571 incrRefCount(zval
.ele
); /* added to skiplist */
1572 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1573 incrRefCount(zval
.ele
); /* added to dictionary */
1577 redisPanic("Unknown operator");
1580 for (i
= 0; i
< setnum
; i
++)
1581 zuiClearIterator(&src
[i
]);
1583 if (dbDelete(c
->db
,dstkey
)) {
1584 signalModifiedKey(c
->db
,dstkey
);
1588 if (dstzset
->zsl
->length
) {
1589 dbAdd(c
->db
,dstkey
,dstobj
);
1590 addReplyLongLong(c
, dstzset
->zsl
->length
);
1591 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1594 decrRefCount(dstobj
);
1595 addReply(c
, shared
.czero
);
1600 void zunionstoreCommand(redisClient
*c
) {
1601 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1604 void zinterstoreCommand(redisClient
*c
) {
1605 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1608 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1609 robj
*key
= c
->argv
[1];
1617 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1618 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1620 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1622 } else if (c
->argc
>= 5) {
1623 addReply(c
,shared
.syntaxerr
);
1627 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1628 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1630 /* Sanitize indexes. */
1631 llen
= zsLength(zobj
);
1632 if (start
< 0) start
= llen
+start
;
1633 if (end
< 0) end
= llen
+end
;
1634 if (start
< 0) start
= 0;
1636 /* Invariant: start >= 0, so this test will be true when end < 0.
1637 * The range is empty when start > end or start >= length. */
1638 if (start
> end
|| start
>= llen
) {
1639 addReply(c
,shared
.emptymultibulk
);
1642 if (end
>= llen
) end
= llen
-1;
1643 rangelen
= (end
-start
)+1;
1645 /* Return the result in form of a multi-bulk reply */
1646 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1648 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1649 unsigned char *zl
= zobj
->ptr
;
1650 unsigned char *eptr
, *sptr
;
1651 unsigned char *vstr
;
1656 eptr
= ziplistIndex(zl
,-2-(2*start
));
1658 eptr
= ziplistIndex(zl
,2*start
);
1660 redisAssert(eptr
!= NULL
);
1661 sptr
= ziplistNext(zl
,eptr
);
1663 while (rangelen
--) {
1664 redisAssert(eptr
!= NULL
&& sptr
!= NULL
);
1665 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1667 addReplyBulkLongLong(c
,vlong
);
1669 addReplyBulkCBuffer(c
,vstr
,vlen
);
1672 addReplyDouble(c
,zzlGetScore(sptr
));
1675 zzlPrev(zl
,&eptr
,&sptr
);
1677 zzlNext(zl
,&eptr
,&sptr
);
1680 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1681 zset
*zs
= zobj
->ptr
;
1682 zskiplist
*zsl
= zs
->zsl
;
1686 /* Check if starting point is trivial, before doing log(N) lookup. */
1690 ln
= zslGetElementByRank(zsl
,llen
-start
);
1692 ln
= zsl
->header
->level
[0].forward
;
1694 ln
= zslGetElementByRank(zsl
,start
+1);
1698 redisAssert(ln
!= NULL
);
1700 addReplyBulk(c
,ele
);
1702 addReplyDouble(c
,ln
->score
);
1703 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1706 redisPanic("Unknown sorted set encoding");
1710 void zrangeCommand(redisClient
*c
) {
1711 zrangeGenericCommand(c
,0);
1714 void zrevrangeCommand(redisClient
*c
) {
1715 zrangeGenericCommand(c
,1);
1718 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1719 * If "justcount", only the number of elements in the range is returned. */
1720 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1722 robj
*key
= c
->argv
[1];
1723 robj
*emptyreply
, *zobj
;
1724 int offset
= 0, limit
= -1;
1726 unsigned long rangelen
= 0;
1727 void *replylen
= NULL
;
1730 /* Parse the range arguments. */
1732 /* Range is given as [max,min] */
1733 maxidx
= 2; minidx
= 3;
1735 /* Range is given as [min,max] */
1736 minidx
= 2; maxidx
= 3;
1739 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1740 addReplyError(c
,"min or max is not a double");
1744 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1745 * 4 arguments, so we'll never enter the following code path. */
1747 int remaining
= c
->argc
- 4;
1751 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1754 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1755 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1756 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1757 pos
+= 3; remaining
-= 3;
1759 addReply(c
,shared
.syntaxerr
);
1765 /* Ok, lookup the key and get the range */
1766 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1767 if ((zobj
= lookupKeyReadOrReply(c
,key
,emptyreply
)) == NULL
||
1768 checkType(c
,zobj
,REDIS_ZSET
)) return;
1770 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1771 unsigned char *zl
= zobj
->ptr
;
1772 unsigned char *eptr
, *sptr
;
1773 unsigned char *vstr
;
1778 /* If reversed, get the last node in range as starting point. */
1780 eptr
= zzlLastInRange(zobj
,range
);
1782 eptr
= zzlFirstInRange(zobj
,range
);
1784 /* No "first" element in the specified interval. */
1786 addReply(c
,emptyreply
);
1790 /* Get score pointer for the first element. */
1791 redisAssert(eptr
!= NULL
);
1792 sptr
= ziplistNext(zl
,eptr
);
1794 /* We don't know in advance how many matching elements there are in the
1795 * list, so we push this object that will represent the multi-bulk
1796 * length in the output buffer, and will "fix" it later */
1798 replylen
= addDeferredMultiBulkLength(c
);
1800 /* If there is an offset, just traverse the number of elements without
1801 * checking the score because that is done in the next loop. */
1802 while (eptr
&& offset
--)
1804 zzlPrev(zl
,&eptr
,&sptr
);
1806 zzlNext(zl
,&eptr
,&sptr
);
1808 while (eptr
&& limit
--) {
1809 score
= zzlGetScore(sptr
);
1811 /* Abort when the node is no longer in range. */
1813 if (!zslValueGteMin(score
,&range
)) break;
1815 if (!zslValueLteMax(score
,&range
)) break;
1821 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1823 addReplyBulkLongLong(c
,vlong
);
1825 addReplyBulkCBuffer(c
,vstr
,vlen
);
1828 addReplyDouble(c
,score
);
1831 /* Move to next node */
1833 zzlPrev(zl
,&eptr
,&sptr
);
1835 zzlNext(zl
,&eptr
,&sptr
);
1837 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1838 zset
*zs
= zobj
->ptr
;
1839 zskiplist
*zsl
= zs
->zsl
;
1842 /* If reversed, get the last node in range as starting point. */
1844 ln
= zslLastInRange(zsl
,range
);
1846 ln
= zslFirstInRange(zsl
,range
);
1848 /* No "first" element in the specified interval. */
1850 addReply(c
,emptyreply
);
1854 /* We don't know in advance how many matching elements there are in the
1855 * list, so we push this object that will represent the multi-bulk
1856 * length in the output buffer, and will "fix" it later */
1858 replylen
= addDeferredMultiBulkLength(c
);
1860 /* If there is an offset, just traverse the number of elements without
1861 * checking the score because that is done in the next loop. */
1862 while (ln
&& offset
--)
1863 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1865 while (ln
&& limit
--) {
1866 /* Abort when the node is no longer in range. */
1868 if (!zslValueGteMin(ln
->score
,&range
)) break;
1870 if (!zslValueLteMax(ln
->score
,&range
)) break;
1876 addReplyBulk(c
,ln
->obj
);
1878 addReplyDouble(c
,ln
->score
);
1881 /* Move to next node */
1882 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1885 redisPanic("Unknown sorted set encoding");
1889 addReplyLongLong(c
,(long)rangelen
);
1891 if (withscores
) rangelen
*= 2;
1892 setDeferredMultiBulkLength(c
,replylen
,rangelen
);
1896 void zrangebyscoreCommand(redisClient
*c
) {
1897 genericZrangebyscoreCommand(c
,0,0);
1900 void zrevrangebyscoreCommand(redisClient
*c
) {
1901 genericZrangebyscoreCommand(c
,1,0);
1904 void zcountCommand(redisClient
*c
) {
1905 genericZrangebyscoreCommand(c
,0,1);
1908 void zcardCommand(redisClient
*c
) {
1909 robj
*key
= c
->argv
[1];
1912 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
1913 checkType(c
,zobj
,REDIS_ZSET
)) return;
1915 addReplyLongLong(c
,zsLength(zobj
));
1918 void zscoreCommand(redisClient
*c
) {
1919 robj
*key
= c
->argv
[1];
1923 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1924 checkType(c
,zobj
,REDIS_ZSET
)) return;
1926 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1927 if (zzlFind(zobj
,c
->argv
[2],&score
) != NULL
)
1928 addReplyDouble(c
,score
);
1930 addReply(c
,shared
.nullbulk
);
1931 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1932 zset
*zs
= zobj
->ptr
;
1935 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1936 de
= dictFind(zs
->dict
,c
->argv
[2]);
1938 score
= *(double*)dictGetEntryVal(de
);
1939 addReplyDouble(c
,score
);
1941 addReply(c
,shared
.nullbulk
);
1944 redisPanic("Unknown sorted set encoding");
1948 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1949 robj
*key
= c
->argv
[1];
1950 robj
*ele
= c
->argv
[2];
1955 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1956 checkType(c
,zobj
,REDIS_ZSET
)) return;
1957 llen
= zsLength(zobj
);
1959 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
1960 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1961 unsigned char *zl
= zobj
->ptr
;
1962 unsigned char *eptr
, *sptr
;
1964 eptr
= ziplistIndex(zl
,0);
1965 redisAssert(eptr
!= NULL
);
1966 sptr
= ziplistNext(zl
,eptr
);
1967 redisAssert(sptr
!= NULL
);
1970 while(eptr
!= NULL
) {
1971 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
1974 zzlNext(zl
,&eptr
,&sptr
);
1979 addReplyLongLong(c
,llen
-rank
);
1981 addReplyLongLong(c
,rank
-1);
1983 addReply(c
,shared
.nullbulk
);
1985 } else if (zobj
->encoding
== REDIS_ENCODING_RAW
) {
1986 zset
*zs
= zobj
->ptr
;
1987 zskiplist
*zsl
= zs
->zsl
;
1991 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1992 de
= dictFind(zs
->dict
,ele
);
1994 score
= *(double*)dictGetEntryVal(de
);
1995 rank
= zslGetRank(zsl
,score
,ele
);
1996 redisAssert(rank
); /* Existing elements always have a rank. */
1998 addReplyLongLong(c
,llen
-rank
);
2000 addReplyLongLong(c
,rank
-1);
2002 addReply(c
,shared
.nullbulk
);
2005 redisPanic("Unknown sorted set encoding");
2009 void zrankCommand(redisClient
*c
) {
2010 zrankGenericCommand(c
, 0);
2013 void zrevrankCommand(redisClient
*c
) {
2014 zrankGenericCommand(c
, 1);