]>
git.saurik.com Git - redis.git/blob - src/t_zset.c
5 /*-----------------------------------------------------------------------------
7 *----------------------------------------------------------------------------*/
9 /* ZSETs are ordered sets using two data structures to hold the same elements
10 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
13 * The elements are added to an hash table mapping Redis objects to scores.
14 * At the same time the elements are added to a skip list mapping scores
15 * to Redis objects (so objects are sorted by scores in this "view"). */
17 /* This skiplist implementation is almost a C translation of the original
18 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
19 * Alternative to Balanced Trees", modified in three ways:
20 * a) this implementation allows for repeated values.
21 * b) the comparison is not just by key (our 'score') but by satellite data.
22 * c) there is a back pointer, so it's a doubly linked list with the back
23 * pointers being only at "level 1". This allows to traverse the list
24 * from tail to head, useful for ZREVRANGE. */
26 zskiplistNode
*zslCreateNode(int level
, double score
, robj
*obj
) {
27 zskiplistNode
*zn
= zmalloc(sizeof(*zn
)+level
*sizeof(struct zskiplistLevel
));
33 zskiplist
*zslCreate(void) {
37 zsl
= zmalloc(sizeof(*zsl
));
40 zsl
->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL
,0,NULL
);
41 for (j
= 0; j
< ZSKIPLIST_MAXLEVEL
; j
++) {
42 zsl
->header
->level
[j
].forward
= NULL
;
43 zsl
->header
->level
[j
].span
= 0;
45 zsl
->header
->backward
= NULL
;
50 void zslFreeNode(zskiplistNode
*node
) {
51 decrRefCount(node
->obj
);
55 void zslFree(zskiplist
*zsl
) {
56 zskiplistNode
*node
= zsl
->header
->level
[0].forward
, *next
;
60 next
= node
->level
[0].forward
;
67 int zslRandomLevel(void) {
69 while ((random()&0xFFFF) < (ZSKIPLIST_P
* 0xFFFF))
71 return (level
<ZSKIPLIST_MAXLEVEL
) ? level
: ZSKIPLIST_MAXLEVEL
;
74 zskiplistNode
*zslInsert(zskiplist
*zsl
, double score
, robj
*obj
) {
75 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
76 unsigned int rank
[ZSKIPLIST_MAXLEVEL
];
80 for (i
= zsl
->level
-1; i
>= 0; i
--) {
81 /* store rank that is crossed to reach the insert position */
82 rank
[i
] = i
== (zsl
->level
-1) ? 0 : rank
[i
+1];
83 while (x
->level
[i
].forward
&&
84 (x
->level
[i
].forward
->score
< score
||
85 (x
->level
[i
].forward
->score
== score
&&
86 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0))) {
87 rank
[i
] += x
->level
[i
].span
;
88 x
= x
->level
[i
].forward
;
92 /* we assume the key is not already inside, since we allow duplicated
93 * scores, and the re-insertion of score and redis object should never
94 * happpen since the caller of zslInsert() should test in the hash table
95 * if the element is already inside or not. */
96 level
= zslRandomLevel();
97 if (level
> zsl
->level
) {
98 for (i
= zsl
->level
; i
< level
; i
++) {
100 update
[i
] = zsl
->header
;
101 update
[i
]->level
[i
].span
= zsl
->length
;
105 x
= zslCreateNode(level
,score
,obj
);
106 for (i
= 0; i
< level
; i
++) {
107 x
->level
[i
].forward
= update
[i
]->level
[i
].forward
;
108 update
[i
]->level
[i
].forward
= x
;
110 /* update span covered by update[i] as x is inserted here */
111 x
->level
[i
].span
= update
[i
]->level
[i
].span
- (rank
[0] - rank
[i
]);
112 update
[i
]->level
[i
].span
= (rank
[0] - rank
[i
]) + 1;
115 /* increment span for untouched levels */
116 for (i
= level
; i
< zsl
->level
; i
++) {
117 update
[i
]->level
[i
].span
++;
120 x
->backward
= (update
[0] == zsl
->header
) ? NULL
: update
[0];
121 if (x
->level
[0].forward
)
122 x
->level
[0].forward
->backward
= x
;
129 /* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
130 void zslDeleteNode(zskiplist
*zsl
, zskiplistNode
*x
, zskiplistNode
**update
) {
132 for (i
= 0; i
< zsl
->level
; i
++) {
133 if (update
[i
]->level
[i
].forward
== x
) {
134 update
[i
]->level
[i
].span
+= x
->level
[i
].span
- 1;
135 update
[i
]->level
[i
].forward
= x
->level
[i
].forward
;
137 update
[i
]->level
[i
].span
-= 1;
140 if (x
->level
[0].forward
) {
141 x
->level
[0].forward
->backward
= x
->backward
;
143 zsl
->tail
= x
->backward
;
145 while(zsl
->level
> 1 && zsl
->header
->level
[zsl
->level
-1].forward
== NULL
)
150 /* Delete an element with matching score/object from the skiplist. */
151 int zslDelete(zskiplist
*zsl
, double score
, robj
*obj
) {
152 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
156 for (i
= zsl
->level
-1; i
>= 0; i
--) {
157 while (x
->level
[i
].forward
&&
158 (x
->level
[i
].forward
->score
< score
||
159 (x
->level
[i
].forward
->score
== score
&&
160 compareStringObjects(x
->level
[i
].forward
->obj
,obj
) < 0)))
161 x
= x
->level
[i
].forward
;
164 /* We may have multiple elements with the same score, what we need
165 * is to find the element with both the right score and object. */
166 x
= x
->level
[0].forward
;
167 if (x
&& score
== x
->score
&& equalStringObjects(x
->obj
,obj
)) {
168 zslDeleteNode(zsl
, x
, update
);
172 return 0; /* not found */
174 return 0; /* not found */
177 /* Struct to hold a inclusive/exclusive range spec. */
180 int minex
, maxex
; /* are min or max exclusive? */
183 static int zslValueGteMin(double value
, zrangespec
*spec
) {
184 return spec
->minex
? (value
> spec
->min
) : (value
>= spec
->min
);
187 static int zslValueLteMax(double value
, zrangespec
*spec
) {
188 return spec
->maxex
? (value
< spec
->max
) : (value
<= spec
->max
);
191 /* Returns if there is a part of the zset is in range. */
192 int zslIsInRange(zskiplist
*zsl
, zrangespec
*range
) {
195 /* Test for ranges that will always be empty. */
196 if (range
->min
> range
->max
||
197 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
200 if (x
== NULL
|| !zslValueGteMin(x
->score
,range
))
202 x
= zsl
->header
->level
[0].forward
;
203 if (x
== NULL
|| !zslValueLteMax(x
->score
,range
))
208 /* Find the first node that is contained in the specified range.
209 * Returns NULL when no element is contained in the range. */
210 zskiplistNode
*zslFirstInRange(zskiplist
*zsl
, zrangespec range
) {
214 /* If everything is out of range, return early. */
215 if (!zslIsInRange(zsl
,&range
)) return NULL
;
218 for (i
= zsl
->level
-1; i
>= 0; i
--) {
219 /* Go forward while *OUT* of range. */
220 while (x
->level
[i
].forward
&&
221 !zslValueGteMin(x
->level
[i
].forward
->score
,&range
))
222 x
= x
->level
[i
].forward
;
225 /* This is an inner range, so the next node cannot be NULL. */
226 x
= x
->level
[0].forward
;
227 redisAssert(x
!= NULL
);
229 /* Check if score <= max. */
230 if (!zslValueLteMax(x
->score
,&range
)) return NULL
;
234 /* Find the last node that is contained in the specified range.
235 * Returns NULL when no element is contained in the range. */
236 zskiplistNode
*zslLastInRange(zskiplist
*zsl
, zrangespec range
) {
240 /* If everything is out of range, return early. */
241 if (!zslIsInRange(zsl
,&range
)) return NULL
;
244 for (i
= zsl
->level
-1; i
>= 0; i
--) {
245 /* Go forward while *IN* range. */
246 while (x
->level
[i
].forward
&&
247 zslValueLteMax(x
->level
[i
].forward
->score
,&range
))
248 x
= x
->level
[i
].forward
;
251 /* This is an inner range, so this node cannot be NULL. */
252 redisAssert(x
!= NULL
);
254 /* Check if score >= min. */
255 if (!zslValueGteMin(x
->score
,&range
)) return NULL
;
259 /* Delete all the elements with score between min and max from the skiplist.
260 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
261 * Note that this function takes the reference to the hash table view of the
262 * sorted set, in order to remove the elements from the hash table too. */
263 unsigned long zslDeleteRangeByScore(zskiplist
*zsl
, zrangespec range
, dict
*dict
) {
264 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
265 unsigned long removed
= 0;
269 for (i
= zsl
->level
-1; i
>= 0; i
--) {
270 while (x
->level
[i
].forward
&& (range
.minex
?
271 x
->level
[i
].forward
->score
<= range
.min
:
272 x
->level
[i
].forward
->score
< range
.min
))
273 x
= x
->level
[i
].forward
;
277 /* Current node is the last with score < or <= min. */
278 x
= x
->level
[0].forward
;
280 /* Delete nodes while in range. */
281 while (x
&& (range
.maxex
? x
->score
< range
.max
: x
->score
<= range
.max
)) {
282 zskiplistNode
*next
= x
->level
[0].forward
;
283 zslDeleteNode(zsl
,x
,update
);
284 dictDelete(dict
,x
->obj
);
292 /* Delete all the elements with rank between start and end from the skiplist.
293 * Start and end are inclusive. Note that start and end need to be 1-based */
294 unsigned long zslDeleteRangeByRank(zskiplist
*zsl
, unsigned int start
, unsigned int end
, dict
*dict
) {
295 zskiplistNode
*update
[ZSKIPLIST_MAXLEVEL
], *x
;
296 unsigned long traversed
= 0, removed
= 0;
300 for (i
= zsl
->level
-1; i
>= 0; i
--) {
301 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) < start
) {
302 traversed
+= x
->level
[i
].span
;
303 x
= x
->level
[i
].forward
;
309 x
= x
->level
[0].forward
;
310 while (x
&& traversed
<= end
) {
311 zskiplistNode
*next
= x
->level
[0].forward
;
312 zslDeleteNode(zsl
,x
,update
);
313 dictDelete(dict
,x
->obj
);
322 /* Find the rank for an element by both score and key.
323 * Returns 0 when the element cannot be found, rank otherwise.
324 * Note that the rank is 1-based due to the span of zsl->header to the
326 unsigned long zslGetRank(zskiplist
*zsl
, double score
, robj
*o
) {
328 unsigned long rank
= 0;
332 for (i
= zsl
->level
-1; i
>= 0; i
--) {
333 while (x
->level
[i
].forward
&&
334 (x
->level
[i
].forward
->score
< score
||
335 (x
->level
[i
].forward
->score
== score
&&
336 compareStringObjects(x
->level
[i
].forward
->obj
,o
) <= 0))) {
337 rank
+= x
->level
[i
].span
;
338 x
= x
->level
[i
].forward
;
341 /* x might be equal to zsl->header, so test if obj is non-NULL */
342 if (x
->obj
&& equalStringObjects(x
->obj
,o
)) {
349 /* Finds an element by its rank. The rank argument needs to be 1-based. */
350 zskiplistNode
* zslGetElementByRank(zskiplist
*zsl
, unsigned long rank
) {
352 unsigned long traversed
= 0;
356 for (i
= zsl
->level
-1; i
>= 0; i
--) {
357 while (x
->level
[i
].forward
&& (traversed
+ x
->level
[i
].span
) <= rank
)
359 traversed
+= x
->level
[i
].span
;
360 x
= x
->level
[i
].forward
;
362 if (traversed
== rank
) {
369 /* Populate the rangespec according to the objects min and max. */
370 static int zslParseRange(robj
*min
, robj
*max
, zrangespec
*spec
) {
372 spec
->minex
= spec
->maxex
= 0;
374 /* Parse the min-max interval. If one of the values is prefixed
375 * by the "(" character, it's considered "open". For instance
376 * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
377 * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
378 if (min
->encoding
== REDIS_ENCODING_INT
) {
379 spec
->min
= (long)min
->ptr
;
381 if (((char*)min
->ptr
)[0] == '(') {
382 spec
->min
= strtod((char*)min
->ptr
+1,&eptr
);
383 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
386 spec
->min
= strtod((char*)min
->ptr
,&eptr
);
387 if (eptr
[0] != '\0' || isnan(spec
->min
)) return REDIS_ERR
;
390 if (max
->encoding
== REDIS_ENCODING_INT
) {
391 spec
->max
= (long)max
->ptr
;
393 if (((char*)max
->ptr
)[0] == '(') {
394 spec
->max
= strtod((char*)max
->ptr
+1,&eptr
);
395 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
398 spec
->max
= strtod((char*)max
->ptr
,&eptr
);
399 if (eptr
[0] != '\0' || isnan(spec
->max
)) return REDIS_ERR
;
406 /*-----------------------------------------------------------------------------
407 * Ziplist-backed sorted set API
408 *----------------------------------------------------------------------------*/
410 double zzlGetScore(unsigned char *sptr
) {
417 redisAssert(sptr
!= NULL
);
418 redisAssert(ziplistGet(sptr
,&vstr
,&vlen
,&vlong
));
421 memcpy(buf
,vstr
,vlen
);
423 score
= strtod(buf
,NULL
);
431 /* Compare element in sorted set with given element. */
432 int zzlCompareElements(unsigned char *eptr
, unsigned char *cstr
, unsigned int clen
) {
436 unsigned char vbuf
[32];
439 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
441 /* Store string representation of long long in buf. */
442 vlen
= ll2string((char*)vbuf
,sizeof(vbuf
),vlong
);
446 minlen
= (vlen
< clen
) ? vlen
: clen
;
447 cmp
= memcmp(vstr
,cstr
,minlen
);
448 if (cmp
== 0) return vlen
-clen
;
452 unsigned int zzlLength(unsigned char *zl
) {
453 return ziplistLen(zl
)/2;
456 /* Move to next entry based on the values in eptr and sptr. Both are set to
457 * NULL when there is no next entry. */
458 void zzlNext(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
459 unsigned char *_eptr
, *_sptr
;
460 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
462 _eptr
= ziplistNext(zl
,*sptr
);
464 _sptr
= ziplistNext(zl
,_eptr
);
465 redisAssert(_sptr
!= NULL
);
475 /* Move to the previous entry based on the values in eptr and sptr. Both are
476 * set to NULL when there is no next entry. */
477 void zzlPrev(unsigned char *zl
, unsigned char **eptr
, unsigned char **sptr
) {
478 unsigned char *_eptr
, *_sptr
;
479 redisAssert(*eptr
!= NULL
&& *sptr
!= NULL
);
481 _sptr
= ziplistPrev(zl
,*eptr
);
483 _eptr
= ziplistPrev(zl
,_sptr
);
484 redisAssert(_eptr
!= NULL
);
486 /* No previous entry. */
494 /* Returns if there is a part of the zset is in range. Should only be used
495 * internally by zzlFirstInRange and zzlLastInRange. */
496 int zzlIsInRange(unsigned char *zl
, zrangespec
*range
) {
500 /* Test for ranges that will always be empty. */
501 if (range
->min
> range
->max
||
502 (range
->min
== range
->max
&& (range
->minex
|| range
->maxex
)))
505 p
= ziplistIndex(zl
,-1); /* Last score. */
506 redisAssert(p
!= NULL
);
507 score
= zzlGetScore(p
);
508 if (!zslValueGteMin(score
,range
))
511 p
= ziplistIndex(zl
,1); /* First score. */
512 redisAssert(p
!= NULL
);
513 score
= zzlGetScore(p
);
514 if (!zslValueLteMax(score
,range
))
520 /* Find pointer to the first element contained in the specified range.
521 * Returns NULL when no element is contained in the range. */
522 unsigned char *zzlFirstInRange(unsigned char *zl
, zrangespec range
) {
523 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
526 /* If everything is out of range, return early. */
527 if (!zzlIsInRange(zl
,&range
)) return NULL
;
529 while (eptr
!= NULL
) {
530 sptr
= ziplistNext(zl
,eptr
);
531 redisAssert(sptr
!= NULL
);
533 score
= zzlGetScore(sptr
);
534 if (zslValueGteMin(score
,&range
)) {
535 /* Check if score <= max. */
536 if (zslValueLteMax(score
,&range
))
541 /* Move to next element. */
542 eptr
= ziplistNext(zl
,sptr
);
548 /* Find pointer to the last element contained in the specified range.
549 * Returns NULL when no element is contained in the range. */
550 unsigned char *zzlLastInRange(unsigned char *zl
, zrangespec range
) {
551 unsigned char *eptr
= ziplistIndex(zl
,-2), *sptr
;
554 /* If everything is out of range, return early. */
555 if (!zzlIsInRange(zl
,&range
)) return NULL
;
557 while (eptr
!= NULL
) {
558 sptr
= ziplistNext(zl
,eptr
);
559 redisAssert(sptr
!= NULL
);
561 score
= zzlGetScore(sptr
);
562 if (zslValueLteMax(score
,&range
)) {
563 /* Check if score >= min. */
564 if (zslValueGteMin(score
,&range
))
569 /* Move to previous element by moving to the score of previous element.
570 * When this returns NULL, we know there also is no element. */
571 sptr
= ziplistPrev(zl
,eptr
);
573 redisAssert((eptr
= ziplistPrev(zl
,sptr
)) != NULL
);
581 unsigned char *zzlFind(unsigned char *zl
, robj
*ele
, double *score
) {
582 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
584 ele
= getDecodedObject(ele
);
585 while (eptr
!= NULL
) {
586 sptr
= ziplistNext(zl
,eptr
);
587 redisAssert(sptr
!= NULL
);
589 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
))) {
590 /* Matching element, pull out score. */
591 if (score
!= NULL
) *score
= zzlGetScore(sptr
);
596 /* Move to next element. */
597 eptr
= ziplistNext(zl
,sptr
);
604 /* Delete (element,score) pair from ziplist. Use local copy of eptr because we
605 * don't want to modify the one given as argument. */
606 unsigned char *zzlDelete(unsigned char *zl
, unsigned char *eptr
) {
607 unsigned char *p
= eptr
;
609 /* TODO: add function to ziplist API to delete N elements from offset. */
610 zl
= ziplistDelete(zl
,&p
);
611 zl
= ziplistDelete(zl
,&p
);
615 unsigned char *zzlInsertAt(unsigned char *zl
, unsigned char *eptr
, robj
*ele
, double score
) {
621 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
622 scorelen
= d2string(scorebuf
,sizeof(scorebuf
),score
);
624 zl
= ziplistPush(zl
,ele
->ptr
,sdslen(ele
->ptr
),ZIPLIST_TAIL
);
625 zl
= ziplistPush(zl
,(unsigned char*)scorebuf
,scorelen
,ZIPLIST_TAIL
);
627 /* Keep offset relative to zl, as it might be re-allocated. */
629 zl
= ziplistInsert(zl
,eptr
,ele
->ptr
,sdslen(ele
->ptr
));
632 /* Insert score after the element. */
633 redisAssert((sptr
= ziplistNext(zl
,eptr
)) != NULL
);
634 zl
= ziplistInsert(zl
,sptr
,(unsigned char*)scorebuf
,scorelen
);
640 /* Insert (element,score) pair in ziplist. This function assumes the element is
641 * not yet present in the list. */
642 unsigned char *zzlInsert(unsigned char *zl
, robj
*ele
, double score
) {
643 unsigned char *eptr
= ziplistIndex(zl
,0), *sptr
;
646 ele
= getDecodedObject(ele
);
647 while (eptr
!= NULL
) {
648 sptr
= ziplistNext(zl
,eptr
);
649 redisAssert(sptr
!= NULL
);
650 s
= zzlGetScore(sptr
);
653 /* First element with score larger than score for element to be
654 * inserted. This means we should take its spot in the list to
655 * maintain ordering. */
656 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
658 } else if (s
== score
) {
659 /* Ensure lexicographical ordering for elements. */
660 if (zzlCompareElements(eptr
,ele
->ptr
,sdslen(ele
->ptr
)) > 0) {
661 zl
= zzlInsertAt(zl
,eptr
,ele
,score
);
666 /* Move to next element. */
667 eptr
= ziplistNext(zl
,sptr
);
670 /* Push on tail of list when it was not yet inserted. */
672 zl
= zzlInsertAt(zl
,NULL
,ele
,score
);
678 unsigned char *zzlDeleteRangeByScore(unsigned char *zl
, zrangespec range
, unsigned long *deleted
) {
679 unsigned char *eptr
, *sptr
;
681 unsigned long num
= 0;
683 if (deleted
!= NULL
) *deleted
= 0;
685 eptr
= zzlFirstInRange(zl
,range
);
686 if (eptr
== NULL
) return zl
;
688 /* When the tail of the ziplist is deleted, eptr will point to the sentinel
689 * byte and ziplistNext will return NULL. */
690 while ((sptr
= ziplistNext(zl
,eptr
)) != NULL
) {
691 score
= zzlGetScore(sptr
);
692 if (zslValueLteMax(score
,&range
)) {
693 /* Delete both the element and the score. */
694 zl
= ziplistDelete(zl
,&eptr
);
695 zl
= ziplistDelete(zl
,&eptr
);
698 /* No longer in range. */
703 if (deleted
!= NULL
) *deleted
= num
;
707 /* Delete all the elements with rank between start and end from the skiplist.
708 * Start and end are inclusive. Note that start and end need to be 1-based */
709 unsigned char *zzlDeleteRangeByRank(unsigned char *zl
, unsigned int start
, unsigned int end
, unsigned long *deleted
) {
710 unsigned int num
= (end
-start
)+1;
711 if (deleted
) *deleted
= num
;
712 zl
= ziplistDeleteRange(zl
,2*(start
-1),2*num
);
716 /*-----------------------------------------------------------------------------
717 * Common sorted set API
718 *----------------------------------------------------------------------------*/
720 unsigned int zsetLength(robj
*zobj
) {
722 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
723 length
= zzlLength(zobj
->ptr
);
724 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
725 length
= ((zset
*)zobj
->ptr
)->zsl
->length
;
727 redisPanic("Unknown sorted set encoding");
732 void zsetConvert(robj
*zobj
, int encoding
) {
734 zskiplistNode
*node
, *next
;
738 if (zobj
->encoding
== encoding
) return;
739 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
740 unsigned char *zl
= zobj
->ptr
;
741 unsigned char *eptr
, *sptr
;
746 if (encoding
!= REDIS_ENCODING_SKIPLIST
)
747 redisPanic("Unknown target encoding");
749 zs
= zmalloc(sizeof(*zs
));
750 zs
->dict
= dictCreate(&zsetDictType
,NULL
);
751 zs
->zsl
= zslCreate();
753 eptr
= ziplistIndex(zl
,0);
754 redisAssert(eptr
!= NULL
);
755 sptr
= ziplistNext(zl
,eptr
);
756 redisAssert(sptr
!= NULL
);
758 while (eptr
!= NULL
) {
759 score
= zzlGetScore(sptr
);
760 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
762 ele
= createStringObjectFromLongLong(vlong
);
764 ele
= createStringObject((char*)vstr
,vlen
);
766 /* Has incremented refcount since it was just created. */
767 node
= zslInsert(zs
->zsl
,score
,ele
);
768 redisAssert(dictAdd(zs
->dict
,ele
,&node
->score
) == DICT_OK
);
769 incrRefCount(ele
); /* Added to dictionary. */
770 zzlNext(zl
,&eptr
,&sptr
);
775 zobj
->encoding
= REDIS_ENCODING_SKIPLIST
;
776 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
777 unsigned char *zl
= ziplistNew();
779 if (encoding
!= REDIS_ENCODING_ZIPLIST
)
780 redisPanic("Unknown target encoding");
782 /* Approach similar to zslFree(), since we want to free the skiplist at
783 * the same time as creating the ziplist. */
785 dictRelease(zs
->dict
);
786 node
= zs
->zsl
->header
->level
[0].forward
;
787 zfree(zs
->zsl
->header
);
791 ele
= getDecodedObject(node
->obj
);
792 zl
= zzlInsertAt(zl
,NULL
,ele
,node
->score
);
795 next
= node
->level
[0].forward
;
802 zobj
->encoding
= REDIS_ENCODING_ZIPLIST
;
804 redisPanic("Unknown sorted set encoding");
808 /*-----------------------------------------------------------------------------
809 * Sorted set commands
810 *----------------------------------------------------------------------------*/
812 /* This generic command implements both ZADD and ZINCRBY. */
813 void zaddGenericCommand(redisClient
*c
, int incr
) {
814 static char *nanerr
= "resulting score is not a number (NaN)";
815 robj
*key
= c
->argv
[1];
819 double score
, curscore
= 0.0;
821 if (getDoubleFromObjectOrReply(c
,c
->argv
[2],&score
,NULL
) != REDIS_OK
)
824 zobj
= lookupKeyWrite(c
->db
,key
);
826 if (server
.zset_max_ziplist_entries
== 0 ||
827 server
.zset_max_ziplist_value
< sdslen(c
->argv
[3]->ptr
))
829 zobj
= createZsetObject();
831 zobj
= createZsetZiplistObject();
833 dbAdd(c
->db
,key
,zobj
);
835 if (zobj
->type
!= REDIS_ZSET
) {
836 addReply(c
,shared
.wrongtypeerr
);
841 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
844 /* Prefer non-encoded element when dealing with ziplists. */
846 if ((eptr
= zzlFind(zobj
->ptr
,ele
,&curscore
)) != NULL
) {
850 addReplyError(c
,nanerr
);
851 /* Don't need to check if the sorted set is empty, because
852 * we know it has at least one element. */
857 /* Remove and re-insert when score changed. */
858 if (score
!= curscore
) {
859 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
860 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
862 signalModifiedKey(c
->db
,key
);
866 if (incr
) /* ZINCRBY */
867 addReplyDouble(c
,score
);
869 addReply(c
,shared
.czero
);
871 /* Optimize: check if the element is too large or the list becomes
872 * too long *before* executing zzlInsert. */
873 zobj
->ptr
= zzlInsert(zobj
->ptr
,ele
,score
);
874 if (zzlLength(zobj
->ptr
) > server
.zset_max_ziplist_entries
)
875 zsetConvert(zobj
,REDIS_ENCODING_SKIPLIST
);
876 if (sdslen(ele
->ptr
) > server
.zset_max_ziplist_value
)
877 zsetConvert(zobj
,REDIS_ENCODING_SKIPLIST
);
879 signalModifiedKey(c
->db
,key
);
882 if (incr
) /* ZINCRBY */
883 addReplyDouble(c
,score
);
885 addReply(c
,shared
.cone
);
887 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
888 zset
*zs
= zobj
->ptr
;
889 zskiplistNode
*znode
;
892 ele
= c
->argv
[3] = tryObjectEncoding(c
->argv
[3]);
893 de
= dictFind(zs
->dict
,ele
);
895 curobj
= dictGetEntryKey(de
);
896 curscore
= *(double*)dictGetEntryVal(de
);
901 addReplyError(c
,nanerr
);
902 /* Don't need to check if the sorted set is empty, because
903 * we know it has at least one element. */
908 /* Remove and re-insert when score changed. We can safely delete
909 * the key object from the skiplist, since the dictionary still has
910 * a reference to it. */
911 if (score
!= curscore
) {
912 redisAssert(zslDelete(zs
->zsl
,curscore
,curobj
));
913 znode
= zslInsert(zs
->zsl
,score
,curobj
);
914 incrRefCount(curobj
); /* Re-inserted in skiplist. */
915 dictGetEntryVal(de
) = &znode
->score
; /* Update score ptr. */
917 signalModifiedKey(c
->db
,key
);
921 if (incr
) /* ZINCRBY */
922 addReplyDouble(c
,score
);
924 addReply(c
,shared
.czero
);
926 znode
= zslInsert(zs
->zsl
,score
,ele
);
927 incrRefCount(ele
); /* Inserted in skiplist. */
928 redisAssert(dictAdd(zs
->dict
,ele
,&znode
->score
) == DICT_OK
);
929 incrRefCount(ele
); /* Added to dictionary. */
931 signalModifiedKey(c
->db
,key
);
934 if (incr
) /* ZINCRBY */
935 addReplyDouble(c
,score
);
937 addReply(c
,shared
.cone
);
940 redisPanic("Unknown sorted set encoding");
944 void zaddCommand(redisClient
*c
) {
945 zaddGenericCommand(c
,0);
948 void zincrbyCommand(redisClient
*c
) {
949 zaddGenericCommand(c
,1);
952 void zremCommand(redisClient
*c
) {
953 robj
*key
= c
->argv
[1];
954 robj
*ele
= c
->argv
[2];
957 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
958 checkType(c
,zobj
,REDIS_ZSET
)) return;
960 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
963 if ((eptr
= zzlFind(zobj
->ptr
,ele
,NULL
)) != NULL
) {
964 zobj
->ptr
= zzlDelete(zobj
->ptr
,eptr
);
965 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
967 addReply(c
,shared
.czero
);
970 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
971 zset
*zs
= zobj
->ptr
;
975 de
= dictFind(zs
->dict
,ele
);
977 /* Delete from the skiplist */
978 score
= *(double*)dictGetEntryVal(de
);
979 redisAssert(zslDelete(zs
->zsl
,score
,ele
));
981 /* Delete from the hash table */
982 dictDelete(zs
->dict
,ele
);
983 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
984 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
986 addReply(c
,shared
.czero
);
990 redisPanic("Unknown sorted set encoding");
993 signalModifiedKey(c
->db
,key
);
995 addReply(c
,shared
.cone
);
998 void zremrangebyscoreCommand(redisClient
*c
) {
999 robj
*key
= c
->argv
[1];
1002 unsigned long deleted
;
1004 /* Parse the range arguments. */
1005 if (zslParseRange(c
->argv
[2],c
->argv
[3],&range
) != REDIS_OK
) {
1006 addReplyError(c
,"min or max is not a double");
1010 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1011 checkType(c
,zobj
,REDIS_ZSET
)) return;
1013 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1014 zobj
->ptr
= zzlDeleteRangeByScore(zobj
->ptr
,range
,&deleted
);
1015 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1016 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1017 zset
*zs
= zobj
->ptr
;
1018 deleted
= zslDeleteRangeByScore(zs
->zsl
,range
,zs
->dict
);
1019 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1020 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1022 redisPanic("Unknown sorted set encoding");
1025 if (deleted
) signalModifiedKey(c
->db
,key
);
1026 server
.dirty
+= deleted
;
1027 addReplyLongLong(c
,deleted
);
1030 void zremrangebyrankCommand(redisClient
*c
) {
1031 robj
*key
= c
->argv
[1];
1036 unsigned long deleted
;
1038 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1039 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1041 if ((zobj
= lookupKeyWriteOrReply(c
,key
,shared
.czero
)) == NULL
||
1042 checkType(c
,zobj
,REDIS_ZSET
)) return;
1044 /* Sanitize indexes. */
1045 llen
= zsetLength(zobj
);
1046 if (start
< 0) start
= llen
+start
;
1047 if (end
< 0) end
= llen
+end
;
1048 if (start
< 0) start
= 0;
1050 /* Invariant: start >= 0, so this test will be true when end < 0.
1051 * The range is empty when start > end or start >= length. */
1052 if (start
> end
|| start
>= llen
) {
1053 addReply(c
,shared
.czero
);
1056 if (end
>= llen
) end
= llen
-1;
1058 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1059 /* Correct for 1-based rank. */
1060 zobj
->ptr
= zzlDeleteRangeByRank(zobj
->ptr
,start
+1,end
+1,&deleted
);
1061 if (zzlLength(zobj
->ptr
) == 0) dbDelete(c
->db
,key
);
1062 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1063 zset
*zs
= zobj
->ptr
;
1065 /* Correct for 1-based rank. */
1066 deleted
= zslDeleteRangeByRank(zs
->zsl
,start
+1,end
+1,zs
->dict
);
1067 if (htNeedsResize(zs
->dict
)) dictResize(zs
->dict
);
1068 if (dictSize(zs
->dict
) == 0) dbDelete(c
->db
,key
);
1070 redisPanic("Unknown sorted set encoding");
1073 if (deleted
) signalModifiedKey(c
->db
,key
);
1074 server
.dirty
+= deleted
;
1075 addReplyLongLong(c
,deleted
);
1080 int type
; /* Set, sorted set */
1085 /* Set iterators. */
1098 /* Sorted set iterators. */
1102 unsigned char *eptr
, *sptr
;
1106 zskiplistNode
*node
;
1113 /* Use dirty flags for pointers that need to be cleaned up in the next
1114 * iteration over the zsetopval. The dirty flag for the long long value is
1115 * special, since long long values don't need cleanup. Instead, it means that
1116 * we already checked that "ell" holds a long long, or tried to convert another
1117 * representation into a long long value. When this was successful,
1118 * OPVAL_VALID_LL is set as well. */
1119 #define OPVAL_DIRTY_ROBJ 1
1120 #define OPVAL_DIRTY_LL 2
1121 #define OPVAL_VALID_LL 4
1123 /* Store value retrieved from the iterator. */
1126 unsigned char _buf
[32]; /* Private buffer. */
1128 unsigned char *estr
;
1134 typedef union _iterset iterset
;
1135 typedef union _iterzset iterzset
;
1137 void zuiInitIterator(zsetopsrc
*op
) {
1138 if (op
->subject
== NULL
)
1141 if (op
->type
== REDIS_SET
) {
1142 iterset
*it
= &op
->iter
.set
;
1143 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1144 it
->is
.is
= op
->subject
->ptr
;
1146 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1147 it
->ht
.dict
= op
->subject
->ptr
;
1148 it
->ht
.di
= dictGetIterator(op
->subject
->ptr
);
1149 it
->ht
.de
= dictNext(it
->ht
.di
);
1151 redisPanic("Unknown set encoding");
1153 } else if (op
->type
== REDIS_ZSET
) {
1154 iterzset
*it
= &op
->iter
.zset
;
1155 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1156 it
->zl
.zl
= op
->subject
->ptr
;
1157 it
->zl
.eptr
= ziplistIndex(it
->zl
.zl
,0);
1158 if (it
->zl
.eptr
!= NULL
) {
1159 it
->zl
.sptr
= ziplistNext(it
->zl
.zl
,it
->zl
.eptr
);
1160 redisAssert(it
->zl
.sptr
!= NULL
);
1162 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1163 it
->sl
.zs
= op
->subject
->ptr
;
1164 it
->sl
.node
= it
->sl
.zs
->zsl
->header
->level
[0].forward
;
1166 redisPanic("Unknown sorted set encoding");
1169 redisPanic("Unsupported type");
1173 void zuiClearIterator(zsetopsrc
*op
) {
1174 if (op
->subject
== NULL
)
1177 if (op
->type
== REDIS_SET
) {
1178 iterset
*it
= &op
->iter
.set
;
1179 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1180 REDIS_NOTUSED(it
); /* skip */
1181 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1182 dictReleaseIterator(it
->ht
.di
);
1184 redisPanic("Unknown set encoding");
1186 } else if (op
->type
== REDIS_ZSET
) {
1187 iterzset
*it
= &op
->iter
.zset
;
1188 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1189 REDIS_NOTUSED(it
); /* skip */
1190 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1191 REDIS_NOTUSED(it
); /* skip */
1193 redisPanic("Unknown sorted set encoding");
1196 redisPanic("Unsupported type");
1200 int zuiLength(zsetopsrc
*op
) {
1201 if (op
->subject
== NULL
)
1204 if (op
->type
== REDIS_SET
) {
1205 iterset
*it
= &op
->iter
.set
;
1206 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1207 return intsetLen(it
->is
.is
);
1208 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1209 return dictSize(it
->ht
.dict
);
1211 redisPanic("Unknown set encoding");
1213 } else if (op
->type
== REDIS_ZSET
) {
1214 iterzset
*it
= &op
->iter
.zset
;
1215 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1216 return zzlLength(it
->zl
.zl
);
1217 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1218 return it
->sl
.zs
->zsl
->length
;
1220 redisPanic("Unknown sorted set encoding");
1223 redisPanic("Unsupported type");
1227 /* Check if the current value is valid. If so, store it in the passed structure
1228 * and move to the next element. If not valid, this means we have reached the
1229 * end of the structure and can abort. */
1230 int zuiNext(zsetopsrc
*op
, zsetopval
*val
) {
1231 if (op
->subject
== NULL
)
1234 if (val
->flags
& OPVAL_DIRTY_ROBJ
)
1235 decrRefCount(val
->ele
);
1237 bzero(val
,sizeof(zsetopval
));
1239 if (op
->type
== REDIS_SET
) {
1240 iterset
*it
= &op
->iter
.set
;
1241 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1242 if (!intsetGet(it
->is
.is
,it
->is
.ii
,&val
->ell
))
1246 /* Move to next element. */
1248 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1249 if (it
->ht
.de
== NULL
)
1251 val
->ele
= dictGetEntryKey(it
->ht
.de
);
1254 /* Move to next element. */
1255 it
->ht
.de
= dictNext(it
->ht
.di
);
1257 redisPanic("Unknown set encoding");
1259 } else if (op
->type
== REDIS_ZSET
) {
1260 iterzset
*it
= &op
->iter
.zset
;
1261 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1262 /* No need to check both, but better be explicit. */
1263 if (it
->zl
.eptr
== NULL
|| it
->zl
.sptr
== NULL
)
1265 redisAssert(ziplistGet(it
->zl
.eptr
,&val
->estr
,&val
->elen
,&val
->ell
));
1266 val
->score
= zzlGetScore(it
->zl
.sptr
);
1268 /* Move to next element. */
1269 zzlNext(it
->zl
.zl
,&it
->zl
.eptr
,&it
->zl
.sptr
);
1270 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1271 if (it
->sl
.node
== NULL
)
1273 val
->ele
= it
->sl
.node
->obj
;
1274 val
->score
= it
->sl
.node
->score
;
1276 /* Move to next element. */
1277 it
->sl
.node
= it
->sl
.node
->level
[0].forward
;
1279 redisPanic("Unknown sorted set encoding");
1282 redisPanic("Unsupported type");
1287 int zuiLongLongFromValue(zsetopval
*val
) {
1288 if (!(val
->flags
& OPVAL_DIRTY_LL
)) {
1289 val
->flags
|= OPVAL_DIRTY_LL
;
1291 if (val
->ele
!= NULL
) {
1292 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1293 val
->ell
= (long)val
->ele
->ptr
;
1294 val
->flags
|= OPVAL_VALID_LL
;
1295 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1296 if (string2ll(val
->ele
->ptr
,sdslen(val
->ele
->ptr
),&val
->ell
))
1297 val
->flags
|= OPVAL_VALID_LL
;
1299 redisPanic("Unsupported element encoding");
1301 } else if (val
->estr
!= NULL
) {
1302 if (string2ll((char*)val
->estr
,val
->elen
,&val
->ell
))
1303 val
->flags
|= OPVAL_VALID_LL
;
1305 /* The long long was already set, flag as valid. */
1306 val
->flags
|= OPVAL_VALID_LL
;
1309 return val
->flags
& OPVAL_VALID_LL
;
1312 robj
*zuiObjectFromValue(zsetopval
*val
) {
1313 if (val
->ele
== NULL
) {
1314 if (val
->estr
!= NULL
) {
1315 val
->ele
= createStringObject((char*)val
->estr
,val
->elen
);
1317 val
->ele
= createStringObjectFromLongLong(val
->ell
);
1319 val
->flags
|= OPVAL_DIRTY_ROBJ
;
1324 int zuiBufferFromValue(zsetopval
*val
) {
1325 if (val
->estr
== NULL
) {
1326 if (val
->ele
!= NULL
) {
1327 if (val
->ele
->encoding
== REDIS_ENCODING_INT
) {
1328 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),(long)val
->ele
->ptr
);
1329 val
->estr
= val
->_buf
;
1330 } else if (val
->ele
->encoding
== REDIS_ENCODING_RAW
) {
1331 val
->elen
= sdslen(val
->ele
->ptr
);
1332 val
->estr
= val
->ele
->ptr
;
1334 redisPanic("Unsupported element encoding");
1337 val
->elen
= ll2string((char*)val
->_buf
,sizeof(val
->_buf
),val
->ell
);
1338 val
->estr
= val
->_buf
;
1344 /* Find value pointed to by val in the source pointer to by op. When found,
1345 * return 1 and store its score in target. Return 0 otherwise. */
1346 int zuiFind(zsetopsrc
*op
, zsetopval
*val
, double *score
) {
1347 if (op
->subject
== NULL
)
1350 if (op
->type
== REDIS_SET
) {
1351 iterset
*it
= &op
->iter
.set
;
1353 if (op
->encoding
== REDIS_ENCODING_INTSET
) {
1354 if (zuiLongLongFromValue(val
) && intsetFind(it
->is
.is
,val
->ell
)) {
1360 } else if (op
->encoding
== REDIS_ENCODING_HT
) {
1361 zuiObjectFromValue(val
);
1362 if (dictFind(it
->ht
.dict
,val
->ele
) != NULL
) {
1369 redisPanic("Unknown set encoding");
1371 } else if (op
->type
== REDIS_ZSET
) {
1372 iterzset
*it
= &op
->iter
.zset
;
1373 zuiObjectFromValue(val
);
1375 if (op
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1376 if (zzlFind(it
->zl
.zl
,val
->ele
,score
) != NULL
) {
1377 /* Score is already set by zzlFind. */
1382 } else if (op
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1384 if ((de
= dictFind(it
->sl
.zs
->dict
,val
->ele
)) != NULL
) {
1385 *score
= *(double*)dictGetEntryVal(de
);
1391 redisPanic("Unknown sorted set encoding");
1394 redisPanic("Unsupported type");
1398 int zuiCompareByCardinality(const void *s1
, const void *s2
) {
1399 return zuiLength((zsetopsrc
*)s1
) - zuiLength((zsetopsrc
*)s2
);
1402 #define REDIS_AGGR_SUM 1
1403 #define REDIS_AGGR_MIN 2
1404 #define REDIS_AGGR_MAX 3
1405 #define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))
1407 inline static void zunionInterAggregate(double *target
, double val
, int aggregate
) {
1408 if (aggregate
== REDIS_AGGR_SUM
) {
1409 *target
= *target
+ val
;
1410 /* The result of adding two doubles is NaN when one variable
1411 * is +inf and the other is -inf. When these numbers are added,
1412 * we maintain the convention of the result being 0.0. */
1413 if (isnan(*target
)) *target
= 0.0;
1414 } else if (aggregate
== REDIS_AGGR_MIN
) {
1415 *target
= val
< *target
? val
: *target
;
1416 } else if (aggregate
== REDIS_AGGR_MAX
) {
1417 *target
= val
> *target
? val
: *target
;
1420 redisPanic("Unknown ZUNION/INTER aggregate type");
1424 void zunionInterGenericCommand(redisClient
*c
, robj
*dstkey
, int op
) {
1426 int aggregate
= REDIS_AGGR_SUM
;
1430 unsigned int maxelelen
= 0;
1433 zskiplistNode
*znode
;
1436 /* expect setnum input keys to be given */
1437 setnum
= atoi(c
->argv
[2]->ptr
);
1440 "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1444 /* test if the expected number of keys would overflow */
1445 if (3+setnum
> c
->argc
) {
1446 addReply(c
,shared
.syntaxerr
);
1450 /* read keys to be used for input */
1451 src
= zcalloc(sizeof(zsetopsrc
) * setnum
);
1452 for (i
= 0, j
= 3; i
< setnum
; i
++, j
++) {
1453 robj
*obj
= lookupKeyWrite(c
->db
,c
->argv
[j
]);
1455 if (obj
->type
!= REDIS_ZSET
&& obj
->type
!= REDIS_SET
) {
1457 addReply(c
,shared
.wrongtypeerr
);
1461 src
[i
].subject
= obj
;
1462 src
[i
].type
= obj
->type
;
1463 src
[i
].encoding
= obj
->encoding
;
1465 src
[i
].subject
= NULL
;
1468 /* Default all weights to 1. */
1469 src
[i
].weight
= 1.0;
1472 /* parse optional extra arguments */
1474 int remaining
= c
->argc
- j
;
1477 if (remaining
>= (setnum
+ 1) && !strcasecmp(c
->argv
[j
]->ptr
,"weights")) {
1479 for (i
= 0; i
< setnum
; i
++, j
++, remaining
--) {
1480 if (getDoubleFromObjectOrReply(c
,c
->argv
[j
],&src
[i
].weight
,
1481 "weight value is not a double") != REDIS_OK
)
1487 } else if (remaining
>= 2 && !strcasecmp(c
->argv
[j
]->ptr
,"aggregate")) {
1489 if (!strcasecmp(c
->argv
[j
]->ptr
,"sum")) {
1490 aggregate
= REDIS_AGGR_SUM
;
1491 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"min")) {
1492 aggregate
= REDIS_AGGR_MIN
;
1493 } else if (!strcasecmp(c
->argv
[j
]->ptr
,"max")) {
1494 aggregate
= REDIS_AGGR_MAX
;
1497 addReply(c
,shared
.syntaxerr
);
1503 addReply(c
,shared
.syntaxerr
);
1509 for (i
= 0; i
< setnum
; i
++)
1510 zuiInitIterator(&src
[i
]);
1512 /* sort sets from the smallest to largest, this will improve our
1513 * algorithm's performance */
1514 qsort(src
,setnum
,sizeof(zsetopsrc
),zuiCompareByCardinality
);
1516 dstobj
= createZsetObject();
1517 dstzset
= dstobj
->ptr
;
1518 memset(&zval
, 0, sizeof(zval
));
1520 if (op
== REDIS_OP_INTER
) {
1521 /* Skip everything if the smallest input is empty. */
1522 if (zuiLength(&src
[0]) > 0) {
1523 /* Precondition: as src[0] is non-empty and the inputs are ordered
1524 * by size, all src[i > 0] are non-empty too. */
1525 while (zuiNext(&src
[0],&zval
)) {
1526 double score
, value
;
1528 score
= src
[0].weight
* zval
.score
;
1529 for (j
= 1; j
< setnum
; j
++) {
1530 if (zuiFind(&src
[j
],&zval
,&value
)) {
1531 value
*= src
[j
].weight
;
1532 zunionInterAggregate(&score
,value
,aggregate
);
1538 /* Only continue when present in every input. */
1540 tmp
= zuiObjectFromValue(&zval
);
1541 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1542 incrRefCount(tmp
); /* added to skiplist */
1543 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1544 incrRefCount(tmp
); /* added to dictionary */
1546 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1547 if (sdslen(tmp
->ptr
) > maxelelen
)
1548 maxelelen
= sdslen(tmp
->ptr
);
1552 } else if (op
== REDIS_OP_UNION
) {
1553 for (i
= 0; i
< setnum
; i
++) {
1554 if (zuiLength(&src
[0]) == 0)
1557 while (zuiNext(&src
[i
],&zval
)) {
1558 double score
, value
;
1560 /* Skip key when already processed */
1561 if (dictFind(dstzset
->dict
,zuiObjectFromValue(&zval
)) != NULL
)
1564 /* Initialize score */
1565 score
= src
[i
].weight
* zval
.score
;
1567 /* Because the inputs are sorted by size, it's only possible
1568 * for sets at larger indices to hold this element. */
1569 for (j
= (i
+1); j
< setnum
; j
++) {
1570 if (zuiFind(&src
[j
],&zval
,&value
)) {
1571 value
*= src
[j
].weight
;
1572 zunionInterAggregate(&score
,value
,aggregate
);
1576 tmp
= zuiObjectFromValue(&zval
);
1577 znode
= zslInsert(dstzset
->zsl
,score
,tmp
);
1578 incrRefCount(zval
.ele
); /* added to skiplist */
1579 dictAdd(dstzset
->dict
,tmp
,&znode
->score
);
1580 incrRefCount(zval
.ele
); /* added to dictionary */
1582 if (tmp
->encoding
== REDIS_ENCODING_RAW
)
1583 if (sdslen(tmp
->ptr
) > maxelelen
)
1584 maxelelen
= sdslen(tmp
->ptr
);
1588 redisPanic("Unknown operator");
1591 for (i
= 0; i
< setnum
; i
++)
1592 zuiClearIterator(&src
[i
]);
1594 if (dbDelete(c
->db
,dstkey
)) {
1595 signalModifiedKey(c
->db
,dstkey
);
1599 if (dstzset
->zsl
->length
) {
1600 /* Convert to ziplist when in limits. */
1601 if (dstzset
->zsl
->length
<= server
.zset_max_ziplist_entries
&&
1602 maxelelen
<= server
.zset_max_ziplist_value
)
1603 zsetConvert(dstobj
,REDIS_ENCODING_ZIPLIST
);
1605 dbAdd(c
->db
,dstkey
,dstobj
);
1606 addReplyLongLong(c
,zsetLength(dstobj
));
1607 if (!touched
) signalModifiedKey(c
->db
,dstkey
);
1610 decrRefCount(dstobj
);
1611 addReply(c
,shared
.czero
);
1616 void zunionstoreCommand(redisClient
*c
) {
1617 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_UNION
);
1620 void zinterstoreCommand(redisClient
*c
) {
1621 zunionInterGenericCommand(c
,c
->argv
[1], REDIS_OP_INTER
);
1624 void zrangeGenericCommand(redisClient
*c
, int reverse
) {
1625 robj
*key
= c
->argv
[1];
1633 if ((getLongFromObjectOrReply(c
, c
->argv
[2], &start
, NULL
) != REDIS_OK
) ||
1634 (getLongFromObjectOrReply(c
, c
->argv
[3], &end
, NULL
) != REDIS_OK
)) return;
1636 if (c
->argc
== 5 && !strcasecmp(c
->argv
[4]->ptr
,"withscores")) {
1638 } else if (c
->argc
>= 5) {
1639 addReply(c
,shared
.syntaxerr
);
1643 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.emptymultibulk
)) == NULL
1644 || checkType(c
,zobj
,REDIS_ZSET
)) return;
1646 /* Sanitize indexes. */
1647 llen
= zsetLength(zobj
);
1648 if (start
< 0) start
= llen
+start
;
1649 if (end
< 0) end
= llen
+end
;
1650 if (start
< 0) start
= 0;
1652 /* Invariant: start >= 0, so this test will be true when end < 0.
1653 * The range is empty when start > end or start >= length. */
1654 if (start
> end
|| start
>= llen
) {
1655 addReply(c
,shared
.emptymultibulk
);
1658 if (end
>= llen
) end
= llen
-1;
1659 rangelen
= (end
-start
)+1;
1661 /* Return the result in form of a multi-bulk reply */
1662 addReplyMultiBulkLen(c
, withscores
? (rangelen
*2) : rangelen
);
1664 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1665 unsigned char *zl
= zobj
->ptr
;
1666 unsigned char *eptr
, *sptr
;
1667 unsigned char *vstr
;
1672 eptr
= ziplistIndex(zl
,-2-(2*start
));
1674 eptr
= ziplistIndex(zl
,2*start
);
1676 redisAssert(eptr
!= NULL
);
1677 sptr
= ziplistNext(zl
,eptr
);
1679 while (rangelen
--) {
1680 redisAssert(eptr
!= NULL
&& sptr
!= NULL
);
1681 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1683 addReplyBulkLongLong(c
,vlong
);
1685 addReplyBulkCBuffer(c
,vstr
,vlen
);
1688 addReplyDouble(c
,zzlGetScore(sptr
));
1691 zzlPrev(zl
,&eptr
,&sptr
);
1693 zzlNext(zl
,&eptr
,&sptr
);
1696 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1697 zset
*zs
= zobj
->ptr
;
1698 zskiplist
*zsl
= zs
->zsl
;
1702 /* Check if starting point is trivial, before doing log(N) lookup. */
1706 ln
= zslGetElementByRank(zsl
,llen
-start
);
1708 ln
= zsl
->header
->level
[0].forward
;
1710 ln
= zslGetElementByRank(zsl
,start
+1);
1714 redisAssert(ln
!= NULL
);
1716 addReplyBulk(c
,ele
);
1718 addReplyDouble(c
,ln
->score
);
1719 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1722 redisPanic("Unknown sorted set encoding");
1726 void zrangeCommand(redisClient
*c
) {
1727 zrangeGenericCommand(c
,0);
1730 void zrevrangeCommand(redisClient
*c
) {
1731 zrangeGenericCommand(c
,1);
1734 /* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
1735 * If "justcount", only the number of elements in the range is returned. */
1736 void genericZrangebyscoreCommand(redisClient
*c
, int reverse
, int justcount
) {
1738 robj
*key
= c
->argv
[1];
1739 robj
*emptyreply
, *zobj
;
1740 int offset
= 0, limit
= -1;
1742 unsigned long rangelen
= 0;
1743 void *replylen
= NULL
;
1746 /* Parse the range arguments. */
1748 /* Range is given as [max,min] */
1749 maxidx
= 2; minidx
= 3;
1751 /* Range is given as [min,max] */
1752 minidx
= 2; maxidx
= 3;
1755 if (zslParseRange(c
->argv
[minidx
],c
->argv
[maxidx
],&range
) != REDIS_OK
) {
1756 addReplyError(c
,"min or max is not a double");
1760 /* Parse optional extra arguments. Note that ZCOUNT will exactly have
1761 * 4 arguments, so we'll never enter the following code path. */
1763 int remaining
= c
->argc
- 4;
1767 if (remaining
>= 1 && !strcasecmp(c
->argv
[pos
]->ptr
,"withscores")) {
1770 } else if (remaining
>= 3 && !strcasecmp(c
->argv
[pos
]->ptr
,"limit")) {
1771 offset
= atoi(c
->argv
[pos
+1]->ptr
);
1772 limit
= atoi(c
->argv
[pos
+2]->ptr
);
1773 pos
+= 3; remaining
-= 3;
1775 addReply(c
,shared
.syntaxerr
);
1781 /* Ok, lookup the key and get the range */
1782 emptyreply
= justcount
? shared
.czero
: shared
.emptymultibulk
;
1783 if ((zobj
= lookupKeyReadOrReply(c
,key
,emptyreply
)) == NULL
||
1784 checkType(c
,zobj
,REDIS_ZSET
)) return;
1786 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1787 unsigned char *zl
= zobj
->ptr
;
1788 unsigned char *eptr
, *sptr
;
1789 unsigned char *vstr
;
1794 /* If reversed, get the last node in range as starting point. */
1796 eptr
= zzlLastInRange(zl
,range
);
1798 eptr
= zzlFirstInRange(zl
,range
);
1800 /* No "first" element in the specified interval. */
1802 addReply(c
,emptyreply
);
1806 /* Get score pointer for the first element. */
1807 redisAssert(eptr
!= NULL
);
1808 sptr
= ziplistNext(zl
,eptr
);
1810 /* We don't know in advance how many matching elements there are in the
1811 * list, so we push this object that will represent the multi-bulk
1812 * length in the output buffer, and will "fix" it later */
1814 replylen
= addDeferredMultiBulkLength(c
);
1816 /* If there is an offset, just traverse the number of elements without
1817 * checking the score because that is done in the next loop. */
1818 while (eptr
&& offset
--)
1820 zzlPrev(zl
,&eptr
,&sptr
);
1822 zzlNext(zl
,&eptr
,&sptr
);
1824 while (eptr
&& limit
--) {
1825 score
= zzlGetScore(sptr
);
1827 /* Abort when the node is no longer in range. */
1829 if (!zslValueGteMin(score
,&range
)) break;
1831 if (!zslValueLteMax(score
,&range
)) break;
1837 redisAssert(ziplistGet(eptr
,&vstr
,&vlen
,&vlong
));
1839 addReplyBulkLongLong(c
,vlong
);
1841 addReplyBulkCBuffer(c
,vstr
,vlen
);
1844 addReplyDouble(c
,score
);
1847 /* Move to next node */
1849 zzlPrev(zl
,&eptr
,&sptr
);
1851 zzlNext(zl
,&eptr
,&sptr
);
1853 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1854 zset
*zs
= zobj
->ptr
;
1855 zskiplist
*zsl
= zs
->zsl
;
1858 /* If reversed, get the last node in range as starting point. */
1860 ln
= zslLastInRange(zsl
,range
);
1862 ln
= zslFirstInRange(zsl
,range
);
1864 /* No "first" element in the specified interval. */
1866 addReply(c
,emptyreply
);
1870 /* We don't know in advance how many matching elements there are in the
1871 * list, so we push this object that will represent the multi-bulk
1872 * length in the output buffer, and will "fix" it later */
1874 replylen
= addDeferredMultiBulkLength(c
);
1876 /* If there is an offset, just traverse the number of elements without
1877 * checking the score because that is done in the next loop. */
1878 while (ln
&& offset
--)
1879 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1881 while (ln
&& limit
--) {
1882 /* Abort when the node is no longer in range. */
1884 if (!zslValueGteMin(ln
->score
,&range
)) break;
1886 if (!zslValueLteMax(ln
->score
,&range
)) break;
1892 addReplyBulk(c
,ln
->obj
);
1894 addReplyDouble(c
,ln
->score
);
1897 /* Move to next node */
1898 ln
= reverse
? ln
->backward
: ln
->level
[0].forward
;
1901 redisPanic("Unknown sorted set encoding");
1905 addReplyLongLong(c
,(long)rangelen
);
1907 if (withscores
) rangelen
*= 2;
1908 setDeferredMultiBulkLength(c
,replylen
,rangelen
);
1912 void zrangebyscoreCommand(redisClient
*c
) {
1913 genericZrangebyscoreCommand(c
,0,0);
1916 void zrevrangebyscoreCommand(redisClient
*c
) {
1917 genericZrangebyscoreCommand(c
,1,0);
1920 void zcountCommand(redisClient
*c
) {
1921 genericZrangebyscoreCommand(c
,0,1);
1924 void zcardCommand(redisClient
*c
) {
1925 robj
*key
= c
->argv
[1];
1928 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.czero
)) == NULL
||
1929 checkType(c
,zobj
,REDIS_ZSET
)) return;
1931 addReplyLongLong(c
,zsetLength(zobj
));
1934 void zscoreCommand(redisClient
*c
) {
1935 robj
*key
= c
->argv
[1];
1939 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1940 checkType(c
,zobj
,REDIS_ZSET
)) return;
1942 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1943 if (zzlFind(zobj
->ptr
,c
->argv
[2],&score
) != NULL
)
1944 addReplyDouble(c
,score
);
1946 addReply(c
,shared
.nullbulk
);
1947 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
1948 zset
*zs
= zobj
->ptr
;
1951 c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
1952 de
= dictFind(zs
->dict
,c
->argv
[2]);
1954 score
= *(double*)dictGetEntryVal(de
);
1955 addReplyDouble(c
,score
);
1957 addReply(c
,shared
.nullbulk
);
1960 redisPanic("Unknown sorted set encoding");
1964 void zrankGenericCommand(redisClient
*c
, int reverse
) {
1965 robj
*key
= c
->argv
[1];
1966 robj
*ele
= c
->argv
[2];
1971 if ((zobj
= lookupKeyReadOrReply(c
,key
,shared
.nullbulk
)) == NULL
||
1972 checkType(c
,zobj
,REDIS_ZSET
)) return;
1973 llen
= zsetLength(zobj
);
1975 redisAssert(ele
->encoding
== REDIS_ENCODING_RAW
);
1976 if (zobj
->encoding
== REDIS_ENCODING_ZIPLIST
) {
1977 unsigned char *zl
= zobj
->ptr
;
1978 unsigned char *eptr
, *sptr
;
1980 eptr
= ziplistIndex(zl
,0);
1981 redisAssert(eptr
!= NULL
);
1982 sptr
= ziplistNext(zl
,eptr
);
1983 redisAssert(sptr
!= NULL
);
1986 while(eptr
!= NULL
) {
1987 if (ziplistCompare(eptr
,ele
->ptr
,sdslen(ele
->ptr
)))
1990 zzlNext(zl
,&eptr
,&sptr
);
1995 addReplyLongLong(c
,llen
-rank
);
1997 addReplyLongLong(c
,rank
-1);
1999 addReply(c
,shared
.nullbulk
);
2001 } else if (zobj
->encoding
== REDIS_ENCODING_SKIPLIST
) {
2002 zset
*zs
= zobj
->ptr
;
2003 zskiplist
*zsl
= zs
->zsl
;
2007 ele
= c
->argv
[2] = tryObjectEncoding(c
->argv
[2]);
2008 de
= dictFind(zs
->dict
,ele
);
2010 score
= *(double*)dictGetEntryVal(de
);
2011 rank
= zslGetRank(zsl
,score
,ele
);
2012 redisAssert(rank
); /* Existing elements always have a rank. */
2014 addReplyLongLong(c
,llen
-rank
);
2016 addReplyLongLong(c
,rank
-1);
2018 addReply(c
,shared
.nullbulk
);
2021 redisPanic("Unknown sorted set encoding");
2025 void zrankCommand(redisClient
*c
) {
2026 zrankGenericCommand(c
, 0);
2029 void zrevrankCommand(redisClient
*c
) {
2030 zrankGenericCommand(c
, 1);