t_zset.c 98.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
 * Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
30 31 32 33 34 35 36 37 38

/*-----------------------------------------------------------------------------
 * Sorted set API
 *----------------------------------------------------------------------------*/

/* ZSETs are ordered sets using two data structures to hold the same elements
 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
 * data structure.
 *
39
 * The elements are added to a hash table mapping Redis objects to scores.
40
 * At the same time the elements are added to a skip list mapping scores
41 42 43 44 45 46 47 48 49 50
 * to Redis objects (so objects are sorted by scores in this "view").
 *
 * Note that the SDS string representing the element is the same in both
 * the hash table and skiplist in order to save memory. What we do in order
 * to manage the shared SDS string more easily is to free the SDS string
 * only in zslFreeNode(). The dictionary has no value free method set.
 * So we should always remove an element from the dictionary, and later from
 * the skiplist.
 *
 * This skiplist implementation is almost a C translation of the original
51 52
 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
 * Alternative to Balanced Trees", modified in three ways:
A
antirez 已提交
53
 * a) this implementation allows for repeated scores.
54 55 56 57 58
 * b) the comparison is not just by key (our 'score') but by satellite data.
 * c) there is a back pointer, so it's a doubly linked list with the back
 * pointers being only at "level 1". This allows to traverse the list
 * from tail to head, useful for ZREVRANGE. */

59
#include "server.h"
60 61
#include <math.h>

62 63 64 65
/*-----------------------------------------------------------------------------
 * Skiplist implementation of the low level API
 *----------------------------------------------------------------------------*/

A
antirez 已提交
66 67
int zslLexValueGteMin(sds value, zlexrangespec *spec);
int zslLexValueLteMax(sds value, zlexrangespec *spec);
A
antirez 已提交
68

69 70 71 72 73
/* Create a skiplist node with the specified number of levels.
 * The SDS string 'ele' is referenced by the node after the call. */
zskiplistNode *zslCreateNode(int level, double score, sds ele) {
    zskiplistNode *zn =
        zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
74
    zn->score = score;
75
    zn->ele = ele;
76 77 78
    return zn;
}

79
/* Create a new skiplist. */
80 81 82 83 84 85 86 87 88
zskiplist *zslCreate(void) {
    int j;
    zskiplist *zsl;

    zsl = zmalloc(sizeof(*zsl));
    zsl->level = 1;
    zsl->length = 0;
    zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
    for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
89 90
        zsl->header->level[j].forward = NULL;
        zsl->header->level[j].span = 0;
91 92 93 94 95 96
    }
    zsl->header->backward = NULL;
    zsl->tail = NULL;
    return zsl;
}

97 98 99
/* Free the specified skiplist node. The referenced SDS string representation
 * of the element is freed too, unless node->ele is set to NULL before calling
 * this function. */
100
void zslFreeNode(zskiplistNode *node) {
101
    sdsfree(node->ele);
102 103 104
    zfree(node);
}

105
/* Free a whole skiplist. */
106
void zslFree(zskiplist *zsl) {
107
    zskiplistNode *node = zsl->header->level[0].forward, *next;
108 109 110

    zfree(zsl->header);
    while(node) {
111
        next = node->level[0].forward;
112 113 114 115 116 117
        zslFreeNode(node);
        node = next;
    }
    zfree(zsl);
}

118 119 120 121
/* Returns a random level for the new skiplist node we are going to create.
 * The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
 * (both inclusive), with a powerlaw-alike distribution where higher
 * levels are less likely to be returned. */
122 123 124 125 126 127 128
int zslRandomLevel(void) {
    int level = 1;
    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
        level += 1;
    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}

129 130 131 132
/* Insert a new node in the skiplist. Assumes the element does not already
 * exist (up to the caller to enforce that). The skiplist takes ownership
 * of the passed SDS string 'ele'. */
zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele) {
133 134 135 136
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned int rank[ZSKIPLIST_MAXLEVEL];
    int i, level;

A
antirez 已提交
137
    serverAssert(!isnan(score));
138 139 140 141
    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* store rank that is crossed to reach the insert position */
        rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
142
        while (x->level[i].forward &&
143 144 145 146
                (x->level[i].forward->score < score ||
                    (x->level[i].forward->score == score &&
                    sdscmp(x->level[i].forward->ele,ele) < 0)))
        {
147 148
            rank[i] += x->level[i].span;
            x = x->level[i].forward;
149 150 151
        }
        update[i] = x;
    }
152 153 154 155
    /* we assume the element is not already inside, since we allow duplicated
     * scores, reinserting the same element should never happen since the
     * caller of zslInsert() should test in the hash table if the element is
     * already inside or not. */
156 157 158 159 160
    level = zslRandomLevel();
    if (level > zsl->level) {
        for (i = zsl->level; i < level; i++) {
            rank[i] = 0;
            update[i] = zsl->header;
161
            update[i]->level[i].span = zsl->length;
162 163 164
        }
        zsl->level = level;
    }
165
    x = zslCreateNode(level,score,ele);
166
    for (i = 0; i < level; i++) {
167 168
        x->level[i].forward = update[i]->level[i].forward;
        update[i]->level[i].forward = x;
169 170

        /* update span covered by update[i] as x is inserted here */
171 172
        x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
        update[i]->level[i].span = (rank[0] - rank[i]) + 1;
173 174 175 176
    }

    /* increment span for untouched levels */
    for (i = level; i < zsl->level; i++) {
177
        update[i]->level[i].span++;
178 179 180
    }

    x->backward = (update[0] == zsl->header) ? NULL : update[0];
181 182
    if (x->level[0].forward)
        x->level[0].forward->backward = x;
183 184 185
    else
        zsl->tail = x;
    zsl->length++;
186
    return x;
187 188 189 190 191 192
}

/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
    int i;
    for (i = 0; i < zsl->level; i++) {
193 194 195
        if (update[i]->level[i].forward == x) {
            update[i]->level[i].span += x->level[i].span - 1;
            update[i]->level[i].forward = x->level[i].forward;
196
        } else {
197
            update[i]->level[i].span -= 1;
198 199
        }
    }
200 201
    if (x->level[0].forward) {
        x->level[0].forward->backward = x->backward;
202 203 204
    } else {
        zsl->tail = x->backward;
    }
205
    while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
206 207 208 209
        zsl->level--;
    zsl->length--;
}

210 211 212 213 214 215 216 217 218
/* Delete an element with matching score/element from the skiplist.
 * The function returns 1 if the node was found and deleted, otherwise
 * 0 is returned.
 *
 * If 'node' is NULL the deleted node is freed by zslFreeNode(), otherwise
 * it is not freed (but just unlinked) and *node is set to the node pointer,
 * so that it is possible for the caller to reuse the node (including the
 * referenced SDS string at node->ele). */
int zslDelete(zskiplist *zsl, double score, sds ele, zskiplistNode **node) {
219 220 221 222 223
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
224
        while (x->level[i].forward &&
225 226 227 228
                (x->level[i].forward->score < score ||
                    (x->level[i].forward->score == score &&
                     sdscmp(x->level[i].forward->ele,ele) < 0)))
        {
229
            x = x->level[i].forward;
230
        }
231 232 233 234
        update[i] = x;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
235
    x = x->level[0].forward;
236
    if (x && score == x->score && sdscmp(x->ele,ele) == 0) {
237
        zslDeleteNode(zsl, x, update);
238 239 240 241
        if (!node)
            zslFreeNode(x);
        else
            *node = x;
242 243 244 245 246
        return 1;
    }
    return 0; /* not found */
}

A
antirez 已提交
247
int zslValueGteMin(double value, zrangespec *spec) {
248 249 250
    return spec->minex ? (value > spec->min) : (value >= spec->min);
}

M
Matt Stancliff 已提交
251
int zslValueLteMax(double value, zrangespec *spec) {
252 253 254 255 256 257 258
    return spec->maxex ? (value < spec->max) : (value <= spec->max);
}

/* Returns if there is a part of the zset is in range. */
int zslIsInRange(zskiplist *zsl, zrangespec *range) {
    zskiplistNode *x;

259 260 261 262
    /* Test for ranges that will always be empty. */
    if (range->min > range->max ||
            (range->min == range->max && (range->minex || range->maxex)))
        return 0;
263
    x = zsl->tail;
P
Pieter Noordhuis 已提交
264
    if (x == NULL || !zslValueGteMin(x->score,range))
265 266
        return 0;
    x = zsl->header->level[0].forward;
P
Pieter Noordhuis 已提交
267
    if (x == NULL || !zslValueLteMax(x->score,range))
268 269 270 271 272 273
        return 0;
    return 1;
}

/* Find the first node that is contained in the specified range.
 * Returns NULL when no element is contained in the range. */
274
zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) {
275 276 277 278
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
279
    if (!zslIsInRange(zsl,range)) return NULL;
280 281 282 283 284

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *OUT* of range. */
        while (x->level[i].forward &&
285
            !zslValueGteMin(x->level[i].forward->score,range))
286 287 288
                x = x->level[i].forward;
    }

289
    /* This is an inner range, so the next node cannot be NULL. */
290
    x = x->level[0].forward;
A
antirez 已提交
291
    serverAssert(x != NULL);
292 293

    /* Check if score <= max. */
294
    if (!zslValueLteMax(x->score,range)) return NULL;
295 296 297 298 299
    return x;
}

/* Find the last node that is contained in the specified range.
 * Returns NULL when no element is contained in the range. */
300
zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) {
301 302 303 304
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
305
    if (!zslIsInRange(zsl,range)) return NULL;
306 307 308 309 310

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *IN* range. */
        while (x->level[i].forward &&
311
            zslValueLteMax(x->level[i].forward->score,range))
312 313 314
                x = x->level[i].forward;
    }

315
    /* This is an inner range, so this node cannot be NULL. */
A
antirez 已提交
316
    serverAssert(x != NULL);
317 318

    /* Check if score >= min. */
319
    if (!zslValueGteMin(x->score,range)) return NULL;
320 321 322
    return x;
}

323
/* Delete all the elements with score between min and max from the skiplist.
G
guiquanz 已提交
324
 * Min and max are inclusive, so a score >= min || score <= max is deleted.
325 326
 * Note that this function takes the reference to the hash table view of the
 * sorted set, in order to remove the elements from the hash table too. */
327
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) {
328 329 330 331 332 333
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
334 335 336
        while (x->level[i].forward && (range->minex ?
            x->level[i].forward->score <= range->min :
            x->level[i].forward->score < range->min))
337
                x = x->level[i].forward;
338 339
        update[i] = x;
    }
340 341

    /* Current node is the last with score < or <= min. */
342
    x = x->level[0].forward;
343 344

    /* Delete nodes while in range. */
345 346 347
    while (x &&
           (range->maxex ? x->score < range->max : x->score <= range->max))
    {
348
        zskiplistNode *next = x->level[0].forward;
349
        zslDeleteNode(zsl,x,update);
350 351
        dictDelete(dict,x->ele);
        zslFreeNode(x); /* Here is where x->ele is actually released. */
352 353 354
        removed++;
        x = next;
    }
355
    return removed;
356 357
}

A
antirez 已提交
358 359 360 361 362 363 364 365 366
unsigned long zslDeleteRangeByLex(zskiplist *zsl, zlexrangespec *range, dict *dict) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long removed = 0;
    int i;


    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward &&
367
            !zslLexValueGteMin(x->level[i].forward->ele,range))
A
antirez 已提交
368 369 370 371 372 373 374 375
                x = x->level[i].forward;
        update[i] = x;
    }

    /* Current node is the last with score < or <= min. */
    x = x->level[0].forward;

    /* Delete nodes while in range. */
376
    while (x && zslLexValueLteMax(x->ele,range)) {
A
antirez 已提交
377 378
        zskiplistNode *next = x->level[0].forward;
        zslDeleteNode(zsl,x,update);
379 380
        dictDelete(dict,x->ele);
        zslFreeNode(x); /* Here is where x->ele is actually released. */
A
antirez 已提交
381 382 383 384 385 386
        removed++;
        x = next;
    }
    return removed;
}

387 388 389 390 391 392 393 394 395
/* Delete all the elements with rank between start and end from the skiplist.
 * Start and end are inclusive. Note that start and end need to be 1-based */
unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long traversed = 0, removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
396 397 398
        while (x->level[i].forward && (traversed + x->level[i].span) < start) {
            traversed += x->level[i].span;
            x = x->level[i].forward;
399 400 401 402 403
        }
        update[i] = x;
    }

    traversed++;
404
    x = x->level[0].forward;
405
    while (x && traversed <= end) {
406
        zskiplistNode *next = x->level[0].forward;
407
        zslDeleteNode(zsl,x,update);
408
        dictDelete(dict,x->ele);
409 410 411 412 413 414 415 416 417 418 419 420
        zslFreeNode(x);
        removed++;
        traversed++;
        x = next;
    }
    return removed;
}

/* Find the rank for an element by both score and key.
 * Returns 0 when the element cannot be found, rank otherwise.
 * Note that the rank is 1-based due to the span of zsl->header to the
 * first element. */
421
unsigned long zslGetRank(zskiplist *zsl, double score, sds ele) {
422 423 424 425 426 427
    zskiplistNode *x;
    unsigned long rank = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
428 429 430
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
431
                sdscmp(x->level[i].forward->ele,ele) <= 0))) {
432 433
            rank += x->level[i].span;
            x = x->level[i].forward;
434 435 436
        }

        /* x might be equal to zsl->header, so test if obj is non-NULL */
437
        if (x->ele && sdscmp(x->ele,ele) == 0) {
438 439 440 441 442 443 444
            return rank;
        }
    }
    return 0;
}

/* Finds an element by its rank. The rank argument needs to be 1-based. */
445
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
446 447 448 449 450 451
    zskiplistNode *x;
    unsigned long traversed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
452
        while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
453
        {
454 455
            traversed += x->level[i].span;
            x = x->level[i].forward;
456 457 458 459 460 461 462 463
        }
        if (traversed == rank) {
            return x;
        }
    }
    return NULL;
}

464
/* Populate the rangespec according to the objects min and max. */
465 466
static int zslParseRange(robj *min, robj *max, zrangespec *spec) {
    char *eptr;
467 468 469 470 471 472
    spec->minex = spec->maxex = 0;

    /* Parse the min-max interval. If one of the values is prefixed
     * by the "(" character, it's considered "open". For instance
     * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
     * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
473
    if (min->encoding == OBJ_ENCODING_INT) {
474 475 476
        spec->min = (long)min->ptr;
    } else {
        if (((char*)min->ptr)[0] == '(') {
477
            spec->min = strtod((char*)min->ptr+1,&eptr);
478
            if (eptr[0] != '\0' || isnan(spec->min)) return C_ERR;
479 480
            spec->minex = 1;
        } else {
481
            spec->min = strtod((char*)min->ptr,&eptr);
482
            if (eptr[0] != '\0' || isnan(spec->min)) return C_ERR;
483 484
        }
    }
485
    if (max->encoding == OBJ_ENCODING_INT) {
486 487 488
        spec->max = (long)max->ptr;
    } else {
        if (((char*)max->ptr)[0] == '(') {
489
            spec->max = strtod((char*)max->ptr+1,&eptr);
490
            if (eptr[0] != '\0' || isnan(spec->max)) return C_ERR;
491 492
            spec->maxex = 1;
        } else {
493
            spec->max = strtod((char*)max->ptr,&eptr);
494
            if (eptr[0] != '\0' || isnan(spec->max)) return C_ERR;
495 496 497
        }
    }

498
    return C_OK;
499 500
}

501 502 503 504 505 506 507 508 509 510
/* ------------------------ Lexicographic ranges ---------------------------- */

/* Parse max or min argument of ZRANGEBYLEX.
  * (foo means foo (open interval)
  * [foo means foo (closed interval)
  * - means the min string possible
  * + means the max string possible
  *
  * If the string is valid the *dest pointer is set to the redis object
  * that will be used for the comparision, and ex will be set to 0 or 1
511
  * respectively if the item is exclusive or inclusive. C_OK will be
512 513
  * returned.
  *
514
  * If the string is not a valid range C_ERR is returned, and the value
515
  * of *dest and *ex is undefined. */
516
int zslParseLexRangeItem(robj *item, sds *dest, int *ex) {
517 518 519 520
    char *c = item->ptr;

    switch(c[0]) {
    case '+':
521
        if (c[1] != '\0') return C_ERR;
522 523
        *ex = 0;
        *dest = shared.maxstring;
524
        return C_OK;
525
    case '-':
526
        if (c[1] != '\0') return C_ERR;
527 528
        *ex = 0;
        *dest = shared.minstring;
529
        return C_OK;
530 531
    case '(':
        *ex = 1;
532
        *dest = sdsnewlen(c+1,sdslen(c)-1);
533
        return C_OK;
534 535
    case '[':
        *ex = 0;
536
        *dest = sdsnewlen(c+1,sdslen(c)-1);
537
        return C_OK;
538
    default:
539
        return C_ERR;
540 541 542
    }
}

543 544 545 546 547 548 549 550 551
/* Free a lex range structure, must be called only after zelParseLexRange()
 * populated the structure with success (C_OK returned). */
void zslFreeLexRange(zlexrangespec *spec) {
    if (spec->min != shared.minstring &&
        spec->min != shared.maxstring) sdsfree(spec->min);
    if (spec->max != shared.minstring &&
        spec->max != shared.maxstring) sdsfree(spec->max);
}

A
antirez 已提交
552
/* Populate the lex rangespec according to the objects min and max.
553
 *
554
 * Return C_OK on success. On error C_ERR is returned.
555 556
 * When OK is returned the structure must be freed with zslFreeLexRange(),
 * otherwise no release is needed. */
A
antirez 已提交
557
int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec) {
558 559
    /* The range can't be valid if objects are integer encoded.
     * Every item must start with ( or [. */
560
    if (min->encoding == OBJ_ENCODING_INT ||
561
        max->encoding == OBJ_ENCODING_INT) return C_ERR;
562 563

    spec->min = spec->max = NULL;
564 565
    if (zslParseLexRangeItem(min, &spec->min, &spec->minex) == C_ERR ||
        zslParseLexRangeItem(max, &spec->max, &spec->maxex) == C_ERR) {
566
        zslFreeLexRange(spec);
567
        return C_ERR;
568
    } else {
569
        return C_OK;
570 571 572
    }
}

573
/* This is just a wrapper to sdscmp() that is able to
574 575
 * handle shared.minstring and shared.maxstring as the equivalent of
 * -inf and +inf for strings */
576 577
int sdscmplex(sds a, sds b) {
    if (a == b) return 0;
578 579
    if (a == shared.minstring || b == shared.maxstring) return -1;
    if (a == shared.maxstring || b == shared.minstring) return 1;
580
    return sdscmp(a,b);
581 582
}

A
antirez 已提交
583
int zslLexValueGteMin(sds value, zlexrangespec *spec) {
584
    return spec->minex ?
585 586
        (sdscmplex(value,spec->min) > 0) :
        (sdscmplex(value,spec->min) >= 0);
587 588
}

A
antirez 已提交
589
int zslLexValueLteMax(sds value, zlexrangespec *spec) {
590
    return spec->maxex ?
591 592
        (sdscmplex(value,spec->max) < 0) :
        (sdscmplex(value,spec->max) <= 0);
593 594 595 596 597 598 599
}

/* Returns if there is a part of the zset is in the lex range. */
int zslIsInLexRange(zskiplist *zsl, zlexrangespec *range) {
    zskiplistNode *x;

    /* Test for ranges that will always be empty. */
600 601
    if (sdscmplex(range->min,range->max) > 1 ||
            (sdscmp(range->min,range->max) == 0 &&
602 603 604
            (range->minex || range->maxex)))
        return 0;
    x = zsl->tail;
605
    if (x == NULL || !zslLexValueGteMin(x->ele,range))
606 607
        return 0;
    x = zsl->header->level[0].forward;
608
    if (x == NULL || !zslLexValueLteMax(x->ele,range))
609 610 611 612 613 614
        return 0;
    return 1;
}

/* Find the first node that is contained in the specified lex range.
 * Returns NULL when no element is contained in the range. */
615
zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range) {
616 617 618 619
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
620
    if (!zslIsInLexRange(zsl,range)) return NULL;
621 622 623 624 625

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *OUT* of range. */
        while (x->level[i].forward &&
626
            !zslLexValueGteMin(x->level[i].forward->ele,range))
627 628 629 630 631
                x = x->level[i].forward;
    }

    /* This is an inner range, so the next node cannot be NULL. */
    x = x->level[0].forward;
A
antirez 已提交
632
    serverAssert(x != NULL);
633 634

    /* Check if score <= max. */
635
    if (!zslLexValueLteMax(x->ele,range)) return NULL;
636 637 638 639 640
    return x;
}

/* Find the last node that is contained in the specified range.
 * Returns NULL when no element is contained in the range. */
641
zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range) {
642 643 644 645
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
646
    if (!zslIsInLexRange(zsl,range)) return NULL;
647 648 649 650 651

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *IN* range. */
        while (x->level[i].forward &&
652
            zslLexValueLteMax(x->level[i].forward->ele,range))
653 654 655 656
                x = x->level[i].forward;
    }

    /* This is an inner range, so this node cannot be NULL. */
A
antirez 已提交
657
    serverAssert(x != NULL);
658 659

    /* Check if score >= min. */
660
    if (!zslLexValueGteMin(x->ele,range)) return NULL;
661 662 663
    return x;
}

664 665 666 667 668 669 670 671 672 673 674
/*-----------------------------------------------------------------------------
 * Ziplist-backed sorted set API
 *----------------------------------------------------------------------------*/

double zzlGetScore(unsigned char *sptr) {
    unsigned char *vstr;
    unsigned int vlen;
    long long vlong;
    char buf[128];
    double score;

A
antirez 已提交
675 676
    serverAssert(sptr != NULL);
    serverAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));
677 678 679 680 681 682 683 684 685 686 687 688

    if (vstr) {
        memcpy(buf,vstr,vlen);
        buf[vlen] = '\0';
        score = strtod(buf,NULL);
    } else {
        score = vlong;
    }

    return score;
}

689 690
/* Return a ziplist element as an SDS string. */
sds ziplistGetObject(unsigned char *sptr) {
691 692 693 694
    unsigned char *vstr;
    unsigned int vlen;
    long long vlong;

A
antirez 已提交
695 696
    serverAssert(sptr != NULL);
    serverAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));
697 698

    if (vstr) {
699
        return sdsnewlen((char*)vstr,vlen);
700
    } else {
701
        return sdsfromlonglong(vlong);
702 703 704
    }
}

705 706 707 708 709 710 711 712
/* Compare element in sorted set with given element. */
int zzlCompareElements(unsigned char *eptr, unsigned char *cstr, unsigned int clen) {
    unsigned char *vstr;
    unsigned int vlen;
    long long vlong;
    unsigned char vbuf[32];
    int minlen, cmp;

A
antirez 已提交
713
    serverAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
714 715 716 717 718 719 720 721 722 723 724 725
    if (vstr == NULL) {
        /* Store string representation of long long in buf. */
        vlen = ll2string((char*)vbuf,sizeof(vbuf),vlong);
        vstr = vbuf;
    }

    minlen = (vlen < clen) ? vlen : clen;
    cmp = memcmp(vstr,cstr,minlen);
    if (cmp == 0) return vlen-clen;
    return cmp;
}

726
unsigned int zzlLength(unsigned char *zl) {
P
Pieter Noordhuis 已提交
727 728 729
    return ziplistLen(zl)/2;
}

730 731 732 733
/* Move to next entry based on the values in eptr and sptr. Both are set to
 * NULL when there is no next entry. */
void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
    unsigned char *_eptr, *_sptr;
A
antirez 已提交
734
    serverAssert(*eptr != NULL && *sptr != NULL);
735 736 737 738

    _eptr = ziplistNext(zl,*sptr);
    if (_eptr != NULL) {
        _sptr = ziplistNext(zl,_eptr);
A
antirez 已提交
739
        serverAssert(_sptr != NULL);
740 741 742 743 744 745 746 747 748 749 750 751 752
    } else {
        /* No next entry. */
        _sptr = NULL;
    }

    *eptr = _eptr;
    *sptr = _sptr;
}

/* Move to the previous entry based on the values in eptr and sptr. Both are
 * set to NULL when there is no next entry. */
void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
    unsigned char *_eptr, *_sptr;
A
antirez 已提交
753
    serverAssert(*eptr != NULL && *sptr != NULL);
754 755 756 757

    _sptr = ziplistPrev(zl,*eptr);
    if (_sptr != NULL) {
        _eptr = ziplistPrev(zl,_sptr);
A
antirez 已提交
758
        serverAssert(_eptr != NULL);
759 760 761 762 763 764 765 766 767
    } else {
        /* No previous entry. */
        _eptr = NULL;
    }

    *eptr = _eptr;
    *sptr = _sptr;
}

768 769 770 771 772 773 774 775 776 777 778 779
/* Returns if there is a part of the zset is in range. Should only be used
 * internally by zzlFirstInRange and zzlLastInRange. */
int zzlIsInRange(unsigned char *zl, zrangespec *range) {
    unsigned char *p;
    double score;

    /* Test for ranges that will always be empty. */
    if (range->min > range->max ||
            (range->min == range->max && (range->minex || range->maxex)))
        return 0;

    p = ziplistIndex(zl,-1); /* Last score. */
780
    if (p == NULL) return 0; /* Empty sorted set */
781 782 783 784 785
    score = zzlGetScore(p);
    if (!zslValueGteMin(score,range))
        return 0;

    p = ziplistIndex(zl,1); /* First score. */
A
antirez 已提交
786
    serverAssert(p != NULL);
787 788 789 790 791 792 793 794 795
    score = zzlGetScore(p);
    if (!zslValueLteMax(score,range))
        return 0;

    return 1;
}

/* Find pointer to the first element contained in the specified range.
 * Returns NULL when no element is contained in the range. */
796
unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range) {
797 798 799 800
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;
    double score;

    /* If everything is out of range, return early. */
801
    if (!zzlIsInRange(zl,range)) return NULL;
802 803 804

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
A
antirez 已提交
805
        serverAssert(sptr != NULL);
806 807

        score = zzlGetScore(sptr);
808
        if (zslValueGteMin(score,range)) {
809
            /* Check if score <= max. */
810
            if (zslValueLteMax(score,range))
811 812 813
                return eptr;
            return NULL;
        }
814 815 816 817 818 819 820 821 822 823

        /* Move to next element. */
        eptr = ziplistNext(zl,sptr);
    }

    return NULL;
}

/* Find pointer to the last element contained in the specified range.
 * Returns NULL when no element is contained in the range. */
824
unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range) {
825 826 827 828
    unsigned char *eptr = ziplistIndex(zl,-2), *sptr;
    double score;

    /* If everything is out of range, return early. */
829
    if (!zzlIsInRange(zl,range)) return NULL;
830 831 832

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
A
antirez 已提交
833
        serverAssert(sptr != NULL);
834 835

        score = zzlGetScore(sptr);
836
        if (zslValueLteMax(score,range)) {
837
            /* Check if score >= min. */
838
            if (zslValueGteMin(score,range))
839 840 841
                return eptr;
            return NULL;
        }
842 843 844 845 846

        /* Move to previous element by moving to the score of previous element.
         * When this returns NULL, we know there also is no element. */
        sptr = ziplistPrev(zl,eptr);
        if (sptr != NULL)
A
antirez 已提交
847
            serverAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
848 849 850 851 852 853 854
        else
            eptr = NULL;
    }

    return NULL;
}

A
antirez 已提交
855
int zzlLexValueGteMin(unsigned char *p, zlexrangespec *spec) {
856
    sds value = ziplistGetObject(p);
857
    int res = zslLexValueGteMin(value,spec);
858
    sdsfree(value);
859 860 861
    return res;
}

A
antirez 已提交
862
int zzlLexValueLteMax(unsigned char *p, zlexrangespec *spec) {
863
    sds value = ziplistGetObject(p);
864
    int res = zslLexValueLteMax(value,spec);
865
    sdsfree(value);
866 867 868 869 870 871 872 873 874
    return res;
}

/* Returns if there is a part of the zset is in range. Should only be used
 * internally by zzlFirstInRange and zzlLastInRange. */
int zzlIsInLexRange(unsigned char *zl, zlexrangespec *range) {
    unsigned char *p;

    /* Test for ranges that will always be empty. */
875 876
    if (sdscmplex(range->min,range->max) > 1 ||
            (sdscmp(range->min,range->max) == 0 &&
877 878 879 880 881 882 883 884 885
            (range->minex || range->maxex)))
        return 0;

    p = ziplistIndex(zl,-2); /* Last element. */
    if (p == NULL) return 0;
    if (!zzlLexValueGteMin(p,range))
        return 0;

    p = ziplistIndex(zl,0); /* First element. */
A
antirez 已提交
886
    serverAssert(p != NULL);
887 888 889 890 891 892 893 894
    if (!zzlLexValueLteMax(p,range))
        return 0;

    return 1;
}

/* Find pointer to the first element contained in the specified lex range.
 * Returns NULL when no element is contained in the range. */
895
unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range) {
896 897 898
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;

    /* If everything is out of range, return early. */
899
    if (!zzlIsInLexRange(zl,range)) return NULL;
900 901

    while (eptr != NULL) {
902
        if (zzlLexValueGteMin(eptr,range)) {
903
            /* Check if score <= max. */
904
            if (zzlLexValueLteMax(eptr,range))
905 906 907 908 909 910
                return eptr;
            return NULL;
        }

        /* Move to next element. */
        sptr = ziplistNext(zl,eptr); /* This element score. Skip it. */
A
antirez 已提交
911
        serverAssert(sptr != NULL);
912 913 914 915 916 917 918 919
        eptr = ziplistNext(zl,sptr); /* Next element. */
    }

    return NULL;
}

/* Find pointer to the last element contained in the specified lex range.
 * Returns NULL when no element is contained in the range. */
920
unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range) {
921 922 923
    unsigned char *eptr = ziplistIndex(zl,-2), *sptr;

    /* If everything is out of range, return early. */
924
    if (!zzlIsInLexRange(zl,range)) return NULL;
925 926

    while (eptr != NULL) {
927
        if (zzlLexValueLteMax(eptr,range)) {
928
            /* Check if score >= min. */
929
            if (zzlLexValueGteMin(eptr,range))
930 931 932 933 934 935 936 937
                return eptr;
            return NULL;
        }

        /* Move to previous element by moving to the score of previous element.
         * When this returns NULL, we know there also is no element. */
        sptr = ziplistPrev(zl,eptr);
        if (sptr != NULL)
A
antirez 已提交
938
            serverAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
939 940 941 942 943 944 945
        else
            eptr = NULL;
    }

    return NULL;
}

946
unsigned char *zzlFind(unsigned char *zl, sds ele, double *score) {
947 948 949 950
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
951
        serverAssert(sptr != NULL);
952

953
        if (ziplistCompare(eptr,(unsigned char*)ele,sdslen(ele))) {
954
            /* Matching element, pull out score. */
P
Pieter Noordhuis 已提交
955
            if (score != NULL) *score = zzlGetScore(sptr);
956 957 958 959 960 961 962 963 964 965 966
            return eptr;
        }

        /* Move to next element. */
        eptr = ziplistNext(zl,sptr);
    }
    return NULL;
}

/* Delete (element,score) pair from ziplist. Use local copy of eptr because we
 * don't want to modify the one given as argument. */
967
unsigned char *zzlDelete(unsigned char *zl, unsigned char *eptr) {
968 969 970 971 972
    unsigned char *p = eptr;

    /* TODO: add function to ziplist API to delete N elements from offset. */
    zl = ziplistDelete(zl,&p);
    zl = ziplistDelete(zl,&p);
973
    return zl;
974 975
}

976
unsigned char *zzlInsertAt(unsigned char *zl, unsigned char *eptr, sds ele, double score) {
977 978 979
    unsigned char *sptr;
    char scorebuf[128];
    int scorelen;
P
Pieter Noordhuis 已提交
980
    size_t offset;
981 982 983

    scorelen = d2string(scorebuf,sizeof(scorebuf),score);
    if (eptr == NULL) {
984
        zl = ziplistPush(zl,(unsigned char*)ele,sdslen(ele),ZIPLIST_TAIL);
985 986 987 988
        zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL);
    } else {
        /* Keep offset relative to zl, as it might be re-allocated. */
        offset = eptr-zl;
989
        zl = ziplistInsert(zl,eptr,(unsigned char*)ele,sdslen(ele));
990 991 992
        eptr = zl+offset;

        /* Insert score after the element. */
993
        serverAssert((sptr = ziplistNext(zl,eptr)) != NULL);
994 995
        zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen);
    }
996
    return zl;
997 998 999 1000
}

/* Insert (element,score) pair in ziplist. This function assumes the element is
 * not yet present in the list. */
1001
unsigned char *zzlInsert(unsigned char *zl, sds ele, double score) {
1002 1003 1004 1005 1006
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;
    double s;

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
1007
        serverAssert(sptr != NULL);
1008 1009 1010 1011 1012 1013
        s = zzlGetScore(sptr);

        if (s > score) {
            /* First element with score larger than score for element to be
             * inserted. This means we should take its spot in the list to
             * maintain ordering. */
1014
            zl = zzlInsertAt(zl,eptr,ele,score);
1015
            break;
P
Pieter Noordhuis 已提交
1016 1017
        } else if (s == score) {
            /* Ensure lexicographical ordering for elements. */
1018
            if (zzlCompareElements(eptr,(unsigned char*)ele,sdslen(ele)) > 0) {
1019
                zl = zzlInsertAt(zl,eptr,ele,score);
P
Pieter Noordhuis 已提交
1020 1021
                break;
            }
1022 1023 1024 1025 1026 1027 1028
        }

        /* Move to next element. */
        eptr = ziplistNext(zl,sptr);
    }

    /* Push on tail of list when it was not yet inserted. */
P
Pieter Noordhuis 已提交
1029
    if (eptr == NULL)
1030 1031
        zl = zzlInsertAt(zl,NULL,ele,score);
    return zl;
1032
}
1033

1034
unsigned char *zzlDeleteRangeByScore(unsigned char *zl, zrangespec *range, unsigned long *deleted) {
1035 1036
    unsigned char *eptr, *sptr;
    double score;
1037
    unsigned long num = 0;
1038

1039
    if (deleted != NULL) *deleted = 0;
1040

1041 1042
    eptr = zzlFirstInRange(zl,range);
    if (eptr == NULL) return zl;
1043 1044 1045 1046 1047

    /* When the tail of the ziplist is deleted, eptr will point to the sentinel
     * byte and ziplistNext will return NULL. */
    while ((sptr = ziplistNext(zl,eptr)) != NULL) {
        score = zzlGetScore(sptr);
1048
        if (zslValueLteMax(score,range)) {
1049 1050 1051
            /* Delete both the element and the score. */
            zl = ziplistDelete(zl,&eptr);
            zl = ziplistDelete(zl,&eptr);
1052
            num++;
1053 1054 1055 1056 1057 1058
        } else {
            /* No longer in range. */
            break;
        }
    }

1059 1060
    if (deleted != NULL) *deleted = num;
    return zl;
1061 1062
}

A
antirez 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
unsigned char *zzlDeleteRangeByLex(unsigned char *zl, zlexrangespec *range, unsigned long *deleted) {
    unsigned char *eptr, *sptr;
    unsigned long num = 0;

    if (deleted != NULL) *deleted = 0;

    eptr = zzlFirstInLexRange(zl,range);
    if (eptr == NULL) return zl;

    /* When the tail of the ziplist is deleted, eptr will point to the sentinel
     * byte and ziplistNext will return NULL. */
    while ((sptr = ziplistNext(zl,eptr)) != NULL) {
        if (zzlLexValueLteMax(eptr,range)) {
            /* Delete both the element and the score. */
            zl = ziplistDelete(zl,&eptr);
            zl = ziplistDelete(zl,&eptr);
            num++;
        } else {
            /* No longer in range. */
            break;
        }
    }

    if (deleted != NULL) *deleted = num;
    return zl;
}

1090 1091
/* Delete all the elements with rank between start and end from the skiplist.
 * Start and end are inclusive. Note that start and end need to be 1-based */
1092
unsigned char *zzlDeleteRangeByRank(unsigned char *zl, unsigned int start, unsigned int end, unsigned long *deleted) {
1093
    unsigned int num = (end-start)+1;
1094 1095 1096
    if (deleted) *deleted = num;
    zl = ziplistDeleteRange(zl,2*(start-1),2*num);
    return zl;
1097 1098
}

1099 1100 1101 1102
/*-----------------------------------------------------------------------------
 * Common sorted set API
 *----------------------------------------------------------------------------*/

1103
unsigned int zsetLength(const robj *zobj) {
1104
    int length = -1;
1105
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1106
        length = zzlLength(zobj->ptr);
1107
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
1108
        length = ((const zset*)zobj->ptr)->zsl->length;
1109
    } else {
A
antirez 已提交
1110
        serverPanic("Unknown sorted set encoding");
1111 1112 1113 1114
    }
    return length;
}

1115
void zsetConvert(robj *zobj, int encoding) {
1116 1117
    zset *zs;
    zskiplistNode *node, *next;
1118
    sds ele;
1119 1120 1121
    double score;

    if (zobj->encoding == encoding) return;
1122
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1123 1124 1125 1126 1127 1128
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

1129
        if (encoding != OBJ_ENCODING_SKIPLIST)
A
antirez 已提交
1130
            serverPanic("Unknown target encoding");
1131 1132 1133 1134 1135 1136

        zs = zmalloc(sizeof(*zs));
        zs->dict = dictCreate(&zsetDictType,NULL);
        zs->zsl = zslCreate();

        eptr = ziplistIndex(zl,0);
A
antirez 已提交
1137
        serverAssertWithInfo(NULL,zobj,eptr != NULL);
1138
        sptr = ziplistNext(zl,eptr);
A
antirez 已提交
1139
        serverAssertWithInfo(NULL,zobj,sptr != NULL);
1140 1141 1142

        while (eptr != NULL) {
            score = zzlGetScore(sptr);
A
antirez 已提交
1143
            serverAssertWithInfo(NULL,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
1144
            if (vstr == NULL)
1145
                ele = sdsfromlonglong(vlong);
1146
            else
1147
                ele = sdsnewlen((char*)vstr,vlen);
1148 1149

            node = zslInsert(zs->zsl,score,ele);
1150
            serverAssert(dictAdd(zs->dict,ele,&node->score) == DICT_OK);
1151 1152 1153 1154 1155
            zzlNext(zl,&eptr,&sptr);
        }

        zfree(zobj->ptr);
        zobj->ptr = zs;
1156 1157
        zobj->encoding = OBJ_ENCODING_SKIPLIST;
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
1158 1159
        unsigned char *zl = ziplistNew();

1160
        if (encoding != OBJ_ENCODING_ZIPLIST)
A
antirez 已提交
1161
            serverPanic("Unknown target encoding");
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

        /* Approach similar to zslFree(), since we want to free the skiplist at
         * the same time as creating the ziplist. */
        zs = zobj->ptr;
        dictRelease(zs->dict);
        node = zs->zsl->header->level[0].forward;
        zfree(zs->zsl->header);
        zfree(zs->zsl);

        while (node) {
1172
            zl = zzlInsertAt(zl,NULL,node->ele,node->score);
1173 1174 1175 1176 1177 1178
            next = node->level[0].forward;
            zslFreeNode(node);
            node = next;
        }

        zfree(zs);
1179
        zobj->ptr = zl;
1180
        zobj->encoding = OBJ_ENCODING_ZIPLIST;
1181
    } else {
A
antirez 已提交
1182
        serverPanic("Unknown sorted set encoding");
1183 1184 1185
    }
}

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
/* Convert the sorted set object into a ziplist if it is not already a ziplist
 * and if the number of elements and the maximum element size is within the
 * expected ranges. */
void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen) {
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) return;
    zset *zset = zobj->ptr;

    if (zset->zsl->length <= server.zset_max_ziplist_entries &&
        maxelelen <= server.zset_max_ziplist_value)
            zsetConvert(zobj,OBJ_ENCODING_ZIPLIST);
}

A
antirez 已提交
1198
/* Return (by reference) the score of the specified member of the sorted set
1199 1200 1201
 * storing it into *score. If the element does not exist C_ERR is returned
 * otherwise C_OK is returned and *score is correctly populated.
 * If 'zobj' or 'member' is NULL, C_ERR is returned. */
1202
int zsetScore(robj *zobj, sds member, double *score) {
1203
    if (!zobj || !member) return C_ERR;
A
antirez 已提交
1204

1205
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1206
        if (zzlFind(zobj->ptr, member, score) == NULL) return C_ERR;
1207
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
1208 1209
        zset *zs = zobj->ptr;
        dictEntry *de = dictFind(zs->dict, member);
1210
        if (de == NULL) return C_ERR;
A
antirez 已提交
1211 1212
        *score = *(double*)dictGetVal(de);
    } else {
A
antirez 已提交
1213
        serverPanic("Unknown sorted set encoding");
A
antirez 已提交
1214
    }
1215
    return C_OK;
A
antirez 已提交
1216 1217
}

A
antirez 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
/* Add a new element or update the score of an existing element in a sorted
 * set, regardless of its encoding.
 *
 * The set of flags change the command behavior. They are passed with an integer
 * pointer since the function will clear the flags and populate them with
 * other flags to indicate different conditions.
 *
 * The input flags are the following:
 *
 * ZADD_INCR: Increment the current element score by 'score' instead of updating
 *            the current element score. If the element does not exist, we
 *            assume 0 as previous score.
 * ZADD_NX:   Perform the operation only if the element does not exist.
 * ZADD_XX:   Perform the operation only if the element already exist.
 *
 * When ZADD_INCR is used, the new score of the element is stored in
 * '*newscore' if 'newscore' is not NULL.
 *
 * The returned flags are the following:
 *
 * ZADD_NAN:     The resulting score is not a number.
 * ZADD_ADDED:   The element was added (not present before the call).
 * ZADD_UPDATED: The element score was updated.
 * ZADD_NOP:     No operation was performed because of NX or XX.
 *
 * Return value:
 *
 * The function returns 1 on success, and sets the appropriate flags
 * ADDED or UPDATED to signal what happened during the operation (note that
 * none could be set if we re-added an element using the same score it used
 * to have, or in the case a zero increment is used).
 *
 * The function returns 0 on erorr, currently only when the increment
 * produces a NAN condition, or when the 'score' value is NAN since the
 * start.
 *
 * The commad as a side effect of adding a new element may convert the sorted
 * set internal encoding from ziplist to hashtable+skiplist.
 *
 * Memory managemnet of 'ele':
 *
 * The function does not take ownership of the 'ele' SDS string, but copies
 * it if needed. */
int zsetAdd(robj *zobj, double score, sds ele, int *flags, double *newscore) {
    /* Turn options into simple to check vars. */
    int incr = (*flags & ZADD_INCR) != 0;
    int nx = (*flags & ZADD_NX) != 0;
    int xx = (*flags & ZADD_XX) != 0;
    *flags = 0; /* We'll return our response flags. */
    double curscore;

    /* NaN as input is an error regardless of all the other parameters. */
    if (isnan(score)) {
        *flags = ZADD_NAN;
        return 0;
    }

    /* Update the sorted set according to its encoding. */
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
        unsigned char *eptr;

        if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
            /* NX? Return, same element already exists. */
            if (nx) {
                *flags |= ZADD_NOP;
                return 1;
            }

            /* Prepare the score for the increment if needed. */
            if (incr) {
                score += curscore;
                if (isnan(score)) {
                    *flags |= ZADD_NAN;
                    return 0;
                }
                if (newscore) *newscore = score;
            }

            /* Remove and re-insert when score changed. */
            if (score != curscore) {
                zobj->ptr = zzlDelete(zobj->ptr,eptr);
                zobj->ptr = zzlInsert(zobj->ptr,ele,score);
                *flags |= ZADD_UPDATED;
            }
            return 1;
        } else if (!xx) {
            /* Optimize: check if the element is too large or the list
             * becomes too long *before* executing zzlInsert. */
            zobj->ptr = zzlInsert(zobj->ptr,ele,score);
            if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries)
                zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);
            if (sdslen(ele) > server.zset_max_ziplist_value)
                zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);
D
Damian Janowski 已提交
1311
            if (newscore) *newscore = score;
A
antirez 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
            *flags |= ZADD_ADDED;
            return 1;
        } else {
            *flags |= ZADD_NOP;
            return 1;
        }
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplistNode *znode;
        dictEntry *de;

        de = dictFind(zs->dict,ele);
        if (de != NULL) {
            /* NX? Return, same element already exists. */
            if (nx) {
                *flags |= ZADD_NOP;
                return 1;
            }
            curscore = *(double*)dictGetVal(de);

            /* Prepare the score for the increment if needed. */
            if (incr) {
                score += curscore;
                if (isnan(score)) {
                    *flags |= ZADD_NAN;
                    return 0;
                }
                if (newscore) *newscore = score;
            }

            /* Remove and re-insert when score changes. */
            if (score != curscore) {
                zskiplistNode *node;
                serverAssert(zslDelete(zs->zsl,curscore,ele,&node));
                znode = zslInsert(zs->zsl,score,node->ele);
                /* We reused the node->ele SDS string, free the node now
                 * since zslInsert created a new one. */
                node->ele = NULL;
                zslFreeNode(node);
                /* Note that we did not removed the original element from
                 * the hash table representing the sorted set, so we just
                 * update the score. */
                dictGetVal(de) = &znode->score; /* Update score ptr. */
                *flags |= ZADD_UPDATED;
            }
            return 1;
        } else if (!xx) {
            ele = sdsdup(ele);
            znode = zslInsert(zs->zsl,score,ele);
            serverAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
            *flags |= ZADD_ADDED;
D
Damian Janowski 已提交
1363
            if (newscore) *newscore = score;
A
antirez 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
            return 1;
        } else {
            *flags |= ZADD_NOP;
            return 1;
        }
    } else {
        serverPanic("Unknown sorted set encoding");
    }
    return 0; /* Never reached. */
}

A
antirez 已提交
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
/* Delete the element 'ele' from the sorted set, returning 1 if the element
 * existed and was deleted, 0 otherwise (the element was not there). */
int zsetDel(robj *zobj, sds ele) {
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
        unsigned char *eptr;

        if ((eptr = zzlFind(zobj->ptr,ele,NULL)) != NULL) {
            zobj->ptr = zzlDelete(zobj->ptr,eptr);
            return 1;
        }
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        dictEntry *de;
        double score;

1390
        de = dictUnlink(zs->dict,ele);
A
antirez 已提交
1391 1392 1393 1394 1395 1396 1397 1398 1399
        if (de != NULL) {
            /* Get the score in order to delete from the skiplist later. */
            score = *(double*)dictGetVal(de);

            /* Delete from the hash table and later from the skiplist.
             * Note that the order is important: deleting from the skiplist
             * actually releases the SDS string representing the element,
             * which is shared between the skiplist and the hash table, so
             * we need to delete from the skiplist as the final step. */
1400
            dictFreeUnlinkedEntry(zs->dict,de);
A
antirez 已提交
1401 1402

            /* Delete from skiplist. */
1403 1404
            int retval = zslDelete(zs->zsl,score,ele,NULL);
            serverAssert(retval);
A
antirez 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

            if (htNeedsResize(zs->dict)) dictResize(zs->dict);
            return 1;
        }
    } else {
        serverPanic("Unknown sorted set encoding");
    }
    return 0; /* No such element found. */
}

A
antirez 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
/* Given a sorted set object returns the 0-based rank of the object or
 * -1 if the object does not exist.
 *
 * For rank we mean the position of the element in the sorted collection
 * of elements. So the first element has rank 0, the second rank 1, and so
 * forth up to length-1 elements.
 *
 * If 'reverse' is false, the rank is returned considering as first element
 * the one with the lowest score. Otherwise if 'reverse' is non-zero
 * the rank is computed considering as element with rank 0 the one with
 * the highest score. */
long zsetRank(robj *zobj, sds ele, int reverse) {
    unsigned long llen;
    unsigned long rank;

    llen = zsetLength(zobj);

    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;

        eptr = ziplistIndex(zl,0);
        serverAssert(eptr != NULL);
        sptr = ziplistNext(zl,eptr);
        serverAssert(sptr != NULL);

        rank = 1;
        while(eptr != NULL) {
            if (ziplistCompare(eptr,(unsigned char*)ele,sdslen(ele)))
                break;
            rank++;
            zzlNext(zl,&eptr,&sptr);
        }

        if (eptr != NULL) {
            if (reverse)
                return llen-rank;
            else
                return rank-1;
        } else {
            return -1;
        }
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        dictEntry *de;
        double score;

        de = dictFind(zs->dict,ele);
        if (de != NULL) {
            score = *(double*)dictGetVal(de);
            rank = zslGetRank(zsl,score,ele);
            /* Existing elements always have a rank. */
            serverAssert(rank != 0);
            if (reverse)
                return llen-rank;
            else
                return rank-1;
        } else {
            return -1;
        }
    } else {
        serverPanic("Unknown sorted set encoding");
    }
}

1481
/*-----------------------------------------------------------------------------
1482
 * Sorted set commands
1483 1484
 *----------------------------------------------------------------------------*/

1485
/* This generic command implements both ZADD and ZINCRBY. */
1486
void zaddGenericCommand(client *c, int flags) {
1487
    static char *nanerr = "resulting score is not a number (NaN)";
1488
    robj *key = c->argv[1];
1489
    robj *zobj;
1490
    sds ele;
A
antirez 已提交
1491
    double score = 0, *scores = NULL;
1492
    int j, elements;
A
antirez 已提交
1493 1494 1495 1496 1497 1498 1499 1500
    int scoreidx = 0;
    /* The following vars are used in order to track what the command actually
     * did during the execution, to reply to the client and to trigger the
     * notification of keyspace change. */
    int added = 0;      /* Number of new elements added. */
    int updated = 0;    /* Number of elements with updated score. */
    int processed = 0;  /* Number of elements processed, may remain zero with
                           options like XX. */
1501 1502 1503 1504 1505 1506 1507 1508

    /* Parse options. At the end 'scoreidx' is set to the argument position
     * of the score of the first score-element pair. */
    scoreidx = 2;
    while(scoreidx < c->argc) {
        char *opt = c->argv[scoreidx]->ptr;
        if (!strcasecmp(opt,"nx")) flags |= ZADD_NX;
        else if (!strcasecmp(opt,"xx")) flags |= ZADD_XX;
A
antirez 已提交
1509
        else if (!strcasecmp(opt,"ch")) flags |= ZADD_CH;
1510 1511 1512 1513 1514 1515 1516 1517 1518
        else if (!strcasecmp(opt,"incr")) flags |= ZADD_INCR;
        else break;
        scoreidx++;
    }

    /* Turn options into simple to check vars. */
    int incr = (flags & ZADD_INCR) != 0;
    int nx = (flags & ZADD_NX) != 0;
    int xx = (flags & ZADD_XX) != 0;
A
antirez 已提交
1519
    int ch = (flags & ZADD_CH) != 0;
1520

1521 1522 1523 1524
    /* After the options, we expect to have an even number of args, since
     * we expect any number of score-element pairs. */
    elements = c->argc-scoreidx;
    if (elements % 2) {
A
antirez 已提交
1525
        addReply(c,shared.syntaxerr);
1526
        return;
A
antirez 已提交
1527
    }
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    elements /= 2; /* Now this holds the number of score-element pairs. */

    /* Check for incompatible options. */
    if (nx && xx) {
        addReplyError(c,
            "XX and NX options at the same time are not compatible");
        return;
    }

    if (incr && elements > 1) {
        addReplyError(c,
            "INCR option supports a single increment-element pair");
        return;
    }
A
antirez 已提交
1542 1543 1544 1545 1546 1547

    /* Start parsing all the scores, we need to emit any syntax error
     * before executing additions to the sorted set, as the command should
     * either execute fully or nothing at all. */
    scores = zmalloc(sizeof(double)*elements);
    for (j = 0; j < elements; j++) {
1548
        if (getDoubleFromObjectOrReply(c,c->argv[scoreidx+j*2],&scores[j],NULL)
1549
            != C_OK) goto cleanup;
A
antirez 已提交
1550
    }
1551

A
antirez 已提交
1552
    /* Lookup the key and create the sorted set if does not exist. */
1553 1554
    zobj = lookupKeyWrite(c->db,key);
    if (zobj == NULL) {
A
antirez 已提交
1555
        if (xx) goto reply_to_client; /* No key + XX option: nothing to do. */
1556
        if (server.zset_max_ziplist_entries == 0 ||
L
linfangrong 已提交
1557
            server.zset_max_ziplist_value < sdslen(c->argv[scoreidx+1]->ptr))
1558 1559 1560 1561 1562
        {
            zobj = createZsetObject();
        } else {
            zobj = createZsetZiplistObject();
        }
1563
        dbAdd(c->db,key,zobj);
1564
    } else {
1565
        if (zobj->type != OBJ_ZSET) {
1566
            addReply(c,shared.wrongtypeerr);
1567
            goto cleanup;
1568 1569 1570
        }
    }

A
antirez 已提交
1571
    for (j = 0; j < elements; j++) {
A
antirez 已提交
1572
        double newscore;
A
antirez 已提交
1573
        score = scores[j];
A
antirez 已提交
1574
        int retflags = flags;
A
antirez 已提交
1575

1576
        ele = c->argv[scoreidx+1+j*2]->ptr;
A
antirez 已提交
1577 1578 1579 1580
        int retval = zsetAdd(zobj, score, ele, &retflags, &newscore);
        if (retval == 0) {
            addReplyError(c,nanerr);
            goto cleanup;
1581
        }
A
antirez 已提交
1582 1583 1584 1585
        if (retflags & ZADD_ADDED) added++;
        if (retflags & ZADD_UPDATED) updated++;
        if (!(retflags & ZADD_NOP)) processed++;
        score = newscore;
1586
    }
A
antirez 已提交
1587
    server.dirty += (added+updated);
A
antirez 已提交
1588 1589 1590 1591 1592 1593 1594 1595

reply_to_client:
    if (incr) { /* ZINCRBY or INCR option. */
        if (processed)
            addReplyDouble(c,score);
        else
            addReply(c,shared.nullbulk);
    } else { /* ZADD. */
A
antirez 已提交
1596
        addReplyLongLong(c,ch ? added+updated : added);
A
antirez 已提交
1597
    }
1598 1599 1600 1601 1602

cleanup:
    zfree(scores);
    if (added || updated) {
        signalModifiedKey(c->db,key);
A
antirez 已提交
1603
        notifyKeyspaceEvent(NOTIFY_ZSET,
1604
            incr ? "zincr" : "zadd", key, c->db->id);
1605
    }
1606 1607
}

1608
void zaddCommand(client *c) {
1609
    zaddGenericCommand(c,ZADD_NONE);
1610 1611
}

1612
void zincrbyCommand(client *c) {
1613
    zaddGenericCommand(c,ZADD_INCR);
1614 1615
}

1616
void zremCommand(client *c) {
P
Pieter Noordhuis 已提交
1617 1618
    robj *key = c->argv[1];
    robj *zobj;
1619
    int deleted = 0, keyremoved = 0, j;
P
Pieter Noordhuis 已提交
1620 1621

    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1622
        checkType(c,zobj,OBJ_ZSET)) return;
P
Pieter Noordhuis 已提交
1623

A
antirez 已提交
1624 1625 1626 1627 1628 1629
    for (j = 2; j < c->argc; j++) {
        if (zsetDel(zobj,c->argv[j]->ptr)) deleted++;
        if (zsetLength(zobj) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
            break;
P
Pieter Noordhuis 已提交
1630
        }
1631 1632
    }

A
antirez 已提交
1633
    if (deleted) {
A
antirez 已提交
1634
        notifyKeyspaceEvent(NOTIFY_ZSET,"zrem",key,c->db->id);
1635
        if (keyremoved)
A
antirez 已提交
1636
            notifyKeyspaceEvent(NOTIFY_GENERIC,"del",key,c->db->id);
A
antirez 已提交
1637 1638 1639 1640
        signalModifiedKey(c->db,key);
        server.dirty += deleted;
    }
    addReplyLongLong(c,deleted);
1641 1642
}

1643 1644 1645 1646
/* Implements ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX commands. */
#define ZRANGE_RANK 0
#define ZRANGE_SCORE 1
#define ZRANGE_LEX 2
1647
void zremrangeGenericCommand(client *c, int rangetype) {
1648 1649
    robj *key = c->argv[1];
    robj *zobj;
1650
    int keyremoved = 0;
1651
    unsigned long deleted = 0;
1652
    zrangespec range;
A
antirez 已提交
1653
    zlexrangespec lexrange;
1654 1655 1656 1657
    long start, end, llen;

    /* Step 1: Parse the range. */
    if (rangetype == ZRANGE_RANK) {
1658 1659
        if ((getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != C_OK) ||
            (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != C_OK))
1660 1661
            return;
    } else if (rangetype == ZRANGE_SCORE) {
1662
        if (zslParseRange(c->argv[2],c->argv[3],&range) != C_OK) {
1663 1664 1665
            addReplyError(c,"min or max is not a float");
            return;
        }
A
antirez 已提交
1666
    } else if (rangetype == ZRANGE_LEX) {
1667
        if (zslParseLexRange(c->argv[2],c->argv[3],&lexrange) != C_OK) {
A
antirez 已提交
1668 1669 1670
            addReplyError(c,"min or max not valid string range item");
            return;
        }
1671
    }
1672

1673
    /* Step 2: Lookup & range sanity checks if needed. */
1674
    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1675
        checkType(c,zobj,OBJ_ZSET)) goto cleanup;
1676

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    if (rangetype == ZRANGE_RANK) {
        /* Sanitize indexes. */
        llen = zsetLength(zobj);
        if (start < 0) start = llen+start;
        if (end < 0) end = llen+end;
        if (start < 0) start = 0;

        /* Invariant: start >= 0, so this test will be true when end < 0.
         * The range is empty when start > end or start >= length. */
        if (start > end || start >= llen) {
            addReply(c,shared.czero);
1688
            goto cleanup;
1689 1690 1691 1692 1693
        }
        if (end >= llen) end = llen-1;
    }

    /* Step 3: Perform the range deletion operation. */
1694
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1695 1696 1697 1698 1699
        switch(rangetype) {
        case ZRANGE_RANK:
            zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted);
            break;
        case ZRANGE_SCORE:
1700
            zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,&range,&deleted);
1701
            break;
A
antirez 已提交
1702 1703 1704
        case ZRANGE_LEX:
            zobj->ptr = zzlDeleteRangeByLex(zobj->ptr,&lexrange,&deleted);
            break;
1705
        }
1706 1707 1708 1709
        if (zzlLength(zobj->ptr) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1710
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
1711
        zset *zs = zobj->ptr;
1712 1713 1714 1715 1716
        switch(rangetype) {
        case ZRANGE_RANK:
            deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
            break;
        case ZRANGE_SCORE:
1717
            deleted = zslDeleteRangeByScore(zs->zsl,&range,zs->dict);
1718
            break;
A
antirez 已提交
1719 1720 1721
        case ZRANGE_LEX:
            deleted = zslDeleteRangeByLex(zs->zsl,&lexrange,zs->dict);
            break;
1722
        }
1723
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1724 1725 1726 1727
        if (dictSize(zs->dict) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1728
    } else {
A
antirez 已提交
1729
        serverPanic("Unknown sorted set encoding");
1730
    }
1731

1732
    /* Step 4: Notifications and reply. */
1733
    if (deleted) {
1734
        char *event[3] = {"zremrangebyrank","zremrangebyscore","zremrangebylex"};
1735
        signalModifiedKey(c->db,key);
A
antirez 已提交
1736
        notifyKeyspaceEvent(NOTIFY_ZSET,event[rangetype],key,c->db->id);
1737
        if (keyremoved)
A
antirez 已提交
1738
            notifyKeyspaceEvent(NOTIFY_GENERIC,"del",key,c->db->id);
1739
    }
1740 1741
    server.dirty += deleted;
    addReplyLongLong(c,deleted);
1742 1743 1744

cleanup:
    if (rangetype == ZRANGE_LEX) zslFreeLexRange(&lexrange);
1745 1746
}

1747
void zremrangebyrankCommand(client *c) {
1748 1749
    zremrangeGenericCommand(c,ZRANGE_RANK);
}
1750

1751
void zremrangebyscoreCommand(client *c) {
1752
    zremrangeGenericCommand(c,ZRANGE_SCORE);
1753 1754
}

1755
void zremrangebylexCommand(client *c) {
A
antirez 已提交
1756 1757 1758
    zremrangeGenericCommand(c,ZRANGE_LEX);
}

1759
typedef struct {
1760 1761 1762
    robj *subject;
    int type; /* Set, sorted set */
    int encoding;
1763
    double weight;
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790

    union {
        /* Set iterators. */
        union _iterset {
            struct {
                intset *is;
                int ii;
            } is;
            struct {
                dict *dict;
                dictIterator *di;
                dictEntry *de;
            } ht;
        } set;

        /* Sorted set iterators. */
        union _iterzset {
            struct {
                unsigned char *zl;
                unsigned char *eptr, *sptr;
            } zl;
            struct {
                zset *zs;
                zskiplistNode *node;
            } sl;
        } zset;
    } iter;
1791 1792
} zsetopsrc;

1793 1794 1795 1796 1797 1798 1799

/* Use dirty flags for pointers that need to be cleaned up in the next
 * iteration over the zsetopval. The dirty flag for the long long value is
 * special, since long long values don't need cleanup. Instead, it means that
 * we already checked that "ell" holds a long long, or tried to convert another
 * representation into a long long value. When this was successful,
 * OPVAL_VALID_LL is set as well. */
1800
#define OPVAL_DIRTY_SDS 1
1801 1802 1803 1804 1805 1806 1807
#define OPVAL_DIRTY_LL 2
#define OPVAL_VALID_LL 4

/* Store value retrieved from the iterator. */
typedef struct {
    int flags;
    unsigned char _buf[32]; /* Private buffer. */
1808
    sds ele;
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
    unsigned char *estr;
    unsigned int elen;
    long long ell;
    double score;
} zsetopval;

typedef union _iterset iterset;
typedef union _iterzset iterzset;

void zuiInitIterator(zsetopsrc *op) {
    if (op->subject == NULL)
        return;

1822
    if (op->type == OBJ_SET) {
1823
        iterset *it = &op->iter.set;
1824
        if (op->encoding == OBJ_ENCODING_INTSET) {
1825 1826
            it->is.is = op->subject->ptr;
            it->is.ii = 0;
1827
        } else if (op->encoding == OBJ_ENCODING_HT) {
1828 1829 1830 1831
            it->ht.dict = op->subject->ptr;
            it->ht.di = dictGetIterator(op->subject->ptr);
            it->ht.de = dictNext(it->ht.di);
        } else {
A
antirez 已提交
1832
            serverPanic("Unknown set encoding");
1833
        }
1834
    } else if (op->type == OBJ_ZSET) {
1835
        iterzset *it = &op->iter.zset;
1836
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1837 1838 1839 1840
            it->zl.zl = op->subject->ptr;
            it->zl.eptr = ziplistIndex(it->zl.zl,0);
            if (it->zl.eptr != NULL) {
                it->zl.sptr = ziplistNext(it->zl.zl,it->zl.eptr);
A
antirez 已提交
1841
                serverAssert(it->zl.sptr != NULL);
1842
            }
1843
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1844 1845 1846
            it->sl.zs = op->subject->ptr;
            it->sl.node = it->sl.zs->zsl->header->level[0].forward;
        } else {
A
antirez 已提交
1847
            serverPanic("Unknown sorted set encoding");
1848 1849
        }
    } else {
A
antirez 已提交
1850
        serverPanic("Unsupported type");
1851 1852 1853 1854 1855 1856 1857
    }
}

void zuiClearIterator(zsetopsrc *op) {
    if (op->subject == NULL)
        return;

1858
    if (op->type == OBJ_SET) {
1859
        iterset *it = &op->iter.set;
1860
        if (op->encoding == OBJ_ENCODING_INTSET) {
A
antirez 已提交
1861
            UNUSED(it); /* skip */
1862
        } else if (op->encoding == OBJ_ENCODING_HT) {
1863 1864
            dictReleaseIterator(it->ht.di);
        } else {
A
antirez 已提交
1865
            serverPanic("Unknown set encoding");
1866
        }
1867
    } else if (op->type == OBJ_ZSET) {
1868
        iterzset *it = &op->iter.zset;
1869
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
A
antirez 已提交
1870
            UNUSED(it); /* skip */
1871
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
1872
            UNUSED(it); /* skip */
1873
        } else {
A
antirez 已提交
1874
            serverPanic("Unknown sorted set encoding");
1875 1876
        }
    } else {
A
antirez 已提交
1877
        serverPanic("Unsupported type");
1878 1879 1880 1881 1882 1883 1884
    }
}

int zuiLength(zsetopsrc *op) {
    if (op->subject == NULL)
        return 0;

1885 1886
    if (op->type == OBJ_SET) {
        if (op->encoding == OBJ_ENCODING_INTSET) {
1887
            return intsetLen(op->subject->ptr);
1888
        } else if (op->encoding == OBJ_ENCODING_HT) {
1889 1890
            dict *ht = op->subject->ptr;
            return dictSize(ht);
1891
        } else {
A
antirez 已提交
1892
            serverPanic("Unknown set encoding");
1893
        }
1894 1895
    } else if (op->type == OBJ_ZSET) {
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1896
            return zzlLength(op->subject->ptr);
1897
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1898 1899
            zset *zs = op->subject->ptr;
            return zs->zsl->length;
1900
        } else {
A
antirez 已提交
1901
            serverPanic("Unknown sorted set encoding");
1902 1903
        }
    } else {
A
antirez 已提交
1904
        serverPanic("Unsupported type");
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
    }
}

/* Check if the current value is valid. If so, store it in the passed structure
 * and move to the next element. If not valid, this means we have reached the
 * end of the structure and can abort. */
int zuiNext(zsetopsrc *op, zsetopval *val) {
    if (op->subject == NULL)
        return 0;

1915 1916
    if (val->flags & OPVAL_DIRTY_SDS)
        sdsfree(val->ele);
1917

A
antirez 已提交
1918
    memset(val,0,sizeof(zsetopval));
1919

1920
    if (op->type == OBJ_SET) {
1921
        iterset *it = &op->iter.set;
1922
        if (op->encoding == OBJ_ENCODING_INTSET) {
1923
            int64_t ell;
A
antirez 已提交
1924 1925

            if (!intsetGet(it->is.is,it->is.ii,&ell))
1926
                return 0;
1927
            val->ell = ell;
1928 1929 1930 1931
            val->score = 1.0;

            /* Move to next element. */
            it->is.ii++;
1932
        } else if (op->encoding == OBJ_ENCODING_HT) {
1933 1934
            if (it->ht.de == NULL)
                return 0;
1935
            val->ele = dictGetKey(it->ht.de);
1936 1937 1938 1939 1940
            val->score = 1.0;

            /* Move to next element. */
            it->ht.de = dictNext(it->ht.di);
        } else {
A
antirez 已提交
1941
            serverPanic("Unknown set encoding");
1942
        }
1943
    } else if (op->type == OBJ_ZSET) {
1944
        iterzset *it = &op->iter.zset;
1945
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1946 1947 1948
            /* No need to check both, but better be explicit. */
            if (it->zl.eptr == NULL || it->zl.sptr == NULL)
                return 0;
A
antirez 已提交
1949
            serverAssert(ziplistGet(it->zl.eptr,&val->estr,&val->elen,&val->ell));
1950 1951 1952 1953
            val->score = zzlGetScore(it->zl.sptr);

            /* Move to next element. */
            zzlNext(it->zl.zl,&it->zl.eptr,&it->zl.sptr);
1954
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1955 1956
            if (it->sl.node == NULL)
                return 0;
1957
            val->ele = it->sl.node->ele;
1958 1959 1960 1961 1962
            val->score = it->sl.node->score;

            /* Move to next element. */
            it->sl.node = it->sl.node->level[0].forward;
        } else {
A
antirez 已提交
1963
            serverPanic("Unknown sorted set encoding");
1964 1965
        }
    } else {
A
antirez 已提交
1966
        serverPanic("Unsupported type");
1967 1968 1969 1970 1971 1972 1973 1974 1975
    }
    return 1;
}

int zuiLongLongFromValue(zsetopval *val) {
    if (!(val->flags & OPVAL_DIRTY_LL)) {
        val->flags |= OPVAL_DIRTY_LL;

        if (val->ele != NULL) {
1976
            if (string2ll(val->ele,sdslen(val->ele),&val->ell))
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
                val->flags |= OPVAL_VALID_LL;
        } else if (val->estr != NULL) {
            if (string2ll((char*)val->estr,val->elen,&val->ell))
                val->flags |= OPVAL_VALID_LL;
        } else {
            /* The long long was already set, flag as valid. */
            val->flags |= OPVAL_VALID_LL;
        }
    }
    return val->flags & OPVAL_VALID_LL;
}

1989
sds zuiSdsFromValue(zsetopval *val) {
1990 1991
    if (val->ele == NULL) {
        if (val->estr != NULL) {
1992
            val->ele = sdsnewlen((char*)val->estr,val->elen);
1993
        } else {
1994
            val->ele = sdsfromlonglong(val->ell);
1995
        }
1996
        val->flags |= OPVAL_DIRTY_SDS;
1997 1998 1999 2000
    }
    return val->ele;
}

2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
/* This is different from zuiSdsFromValue since returns a new SDS string
 * which is up to the caller to free. */
sds zuiNewSdsFromValue(zsetopval *val) {
    if (val->flags & OPVAL_DIRTY_SDS) {
        /* We have already one to return! */
        sds ele = val->ele;
        val->flags &= ~OPVAL_DIRTY_SDS;
        val->ele = NULL;
        return ele;
    } else if (val->ele) {
        return sdsdup(val->ele);
    } else if (val->estr) {
        return sdsnewlen((char*)val->estr,val->elen);
    } else {
        return sdsfromlonglong(val->ell);
    }
}

2019 2020 2021
int zuiBufferFromValue(zsetopval *val) {
    if (val->estr == NULL) {
        if (val->ele != NULL) {
2022 2023
            val->elen = sdslen(val->ele);
            val->estr = (unsigned char*)val->ele;
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        } else {
            val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),val->ell);
            val->estr = val->_buf;
        }
    }
    return 1;
}

/* Find value pointed to by val in the source pointer to by op. When found,
 * return 1 and store its score in target. Return 0 otherwise. */
int zuiFind(zsetopsrc *op, zsetopval *val, double *score) {
    if (op->subject == NULL)
        return 0;

2038 2039
    if (op->type == OBJ_SET) {
        if (op->encoding == OBJ_ENCODING_INTSET) {
2040 2041 2042
            if (zuiLongLongFromValue(val) &&
                intsetFind(op->subject->ptr,val->ell))
            {
2043 2044 2045 2046 2047
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
2048
        } else if (op->encoding == OBJ_ENCODING_HT) {
2049
            dict *ht = op->subject->ptr;
2050
            zuiSdsFromValue(val);
2051
            if (dictFind(ht,val->ele) != NULL) {
2052 2053 2054 2055 2056 2057
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else {
A
antirez 已提交
2058
            serverPanic("Unknown set encoding");
2059
        }
2060
    } else if (op->type == OBJ_ZSET) {
2061
        zuiSdsFromValue(val);
2062

2063
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
2064
            if (zzlFind(op->subject->ptr,val->ele,score) != NULL) {
2065 2066 2067 2068 2069
                /* Score is already set by zzlFind. */
                return 1;
            } else {
                return 0;
            }
2070
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
2071
            zset *zs = op->subject->ptr;
2072
            dictEntry *de;
2073
            if ((de = dictFind(zs->dict,val->ele)) != NULL) {
2074
                *score = *(double*)dictGetVal(de);
2075 2076 2077 2078 2079
                return 1;
            } else {
                return 0;
            }
        } else {
A
antirez 已提交
2080
            serverPanic("Unknown sorted set encoding");
2081 2082
        }
    } else {
A
antirez 已提交
2083
        serverPanic("Unsupported type");
2084 2085 2086 2087 2088
    }
}

int zuiCompareByCardinality(const void *s1, const void *s2) {
    return zuiLength((zsetopsrc*)s1) - zuiLength((zsetopsrc*)s2);
2089 2090 2091 2092 2093
}

#define REDIS_AGGR_SUM 1
#define REDIS_AGGR_MIN 2
#define REDIS_AGGR_MAX 3
2094
#define zunionInterDictValue(_e) (dictGetVal(_e) == NULL ? 1.0 : *(double*)dictGetVal(_e))
2095 2096 2097 2098

inline static void zunionInterAggregate(double *target, double val, int aggregate) {
    if (aggregate == REDIS_AGGR_SUM) {
        *target = *target + val;
2099 2100 2101 2102
        /* The result of adding two doubles is NaN when one variable
         * is +inf and the other is -inf. When these numbers are added,
         * we maintain the convention of the result being 0.0. */
        if (isnan(*target)) *target = 0.0;
2103 2104 2105 2106 2107 2108
    } else if (aggregate == REDIS_AGGR_MIN) {
        *target = val < *target ? val : *target;
    } else if (aggregate == REDIS_AGGR_MAX) {
        *target = val > *target ? val : *target;
    } else {
        /* safety net */
A
antirez 已提交
2109
        serverPanic("Unknown ZUNION/INTER aggregate type");
2110 2111 2112
    }
}

2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
unsigned int dictSdsHash(const void *key);
int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2);

dictType setAccumulatorDictType = {
    dictSdsHash,               /* hash function */
    NULL,                      /* key dup */
    NULL,                      /* val dup */
    dictSdsKeyCompare,         /* key compare */
    NULL,                      /* key destructor */
    NULL                       /* val destructor */
};

2125
void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
2126 2127
    int i, j;
    long setnum;
2128 2129
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
2130
    zsetopval zval;
2131
    sds tmp;
2132
    unsigned int maxelelen = 0;
2133 2134
    robj *dstobj;
    zset *dstzset;
2135
    zskiplistNode *znode;
2136
    int touched = 0;
2137 2138

    /* expect setnum input keys to be given */
2139
    if ((getLongFromObjectOrReply(c, c->argv[2], &setnum, NULL) != C_OK))
2140 2141
        return;

2142
    if (setnum < 1) {
2143 2144
        addReplyError(c,
            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
2145 2146 2147 2148
        return;
    }

    /* test if the expected number of keys would overflow */
2149
    if (setnum > c->argc-3) {
2150 2151 2152 2153 2154
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
2155
    src = zcalloc(sizeof(zsetopsrc) * setnum);
2156 2157
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
2158
        if (obj != NULL) {
2159
            if (obj->type != OBJ_ZSET && obj->type != OBJ_SET) {
2160 2161 2162 2163
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
2164 2165 2166 2167 2168 2169

            src[i].subject = obj;
            src[i].type = obj->type;
            src[i].encoding = obj->encoding;
        } else {
            src[i].subject = NULL;
2170 2171
        }

2172
        /* Default all weights to 1. */
2173 2174 2175 2176 2177 2178 2179 2180
        src[i].weight = 1.0;
    }

    /* parse optional extra arguments */
    if (j < c->argc) {
        int remaining = c->argc - j;

        while (remaining) {
2181 2182 2183
            if (remaining >= (setnum + 1) &&
                !strcasecmp(c->argv[j]->ptr,"weights"))
            {
2184 2185
                j++; remaining--;
                for (i = 0; i < setnum; i++, j++, remaining--) {
2186
                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
2187
                            "weight value is not a float") != C_OK)
2188 2189
                    {
                        zfree(src);
2190
                        return;
2191
                    }
2192
                }
2193 2194 2195
            } else if (remaining >= 2 &&
                       !strcasecmp(c->argv[j]->ptr,"aggregate"))
            {
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
                j++; remaining--;
                if (!strcasecmp(c->argv[j]->ptr,"sum")) {
                    aggregate = REDIS_AGGR_SUM;
                } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
                    aggregate = REDIS_AGGR_MIN;
                } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
                    aggregate = REDIS_AGGR_MAX;
                } else {
                    zfree(src);
                    addReply(c,shared.syntaxerr);
                    return;
                }
                j++; remaining--;
            } else {
                zfree(src);
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* sort sets from the smallest to largest, this will improve our
     * algorithm's performance */
2219
    qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality);
2220 2221 2222

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;
2223
    memset(&zval, 0, sizeof(zval));
2224

A
antirez 已提交
2225
    if (op == SET_OP_INTER) {
2226 2227 2228 2229
        /* Skip everything if the smallest input is empty. */
        if (zuiLength(&src[0]) > 0) {
            /* Precondition: as src[0] is non-empty and the inputs are ordered
             * by size, all src[i > 0] are non-empty too. */
2230
            zuiInitIterator(&src[0]);
2231
            while (zuiNext(&src[0],&zval)) {
2232
                double score, value;
2233

2234
                score = src[0].weight * zval.score;
2235 2236
                if (isnan(score)) score = 0;

2237
                for (j = 1; j < setnum; j++) {
A
antirez 已提交
2238
                    /* It is not safe to access the zset we are
2239
                     * iterating, so explicitly check for equal object. */
2240 2241 2242 2243
                    if (src[j].subject == src[0].subject) {
                        value = zval.score*src[j].weight;
                        zunionInterAggregate(&score,value,aggregate);
                    } else if (zuiFind(&src[j],&zval,&value)) {
2244
                        value *= src[j].weight;
2245
                        zunionInterAggregate(&score,value,aggregate);
2246 2247 2248 2249 2250
                    } else {
                        break;
                    }
                }

2251
                /* Only continue when present in every input. */
2252
                if (j == setnum) {
2253
                    tmp = zuiNewSdsFromValue(&zval);
2254 2255
                    znode = zslInsert(dstzset->zsl,score,tmp);
                    dictAdd(dstzset->dict,tmp,&znode->score);
2256
                    if (sdslen(tmp) > maxelelen) maxelelen = sdslen(tmp);
2257 2258
                }
            }
2259
            zuiClearIterator(&src[0]);
2260
        }
A
antirez 已提交
2261
    } else if (op == SET_OP_UNION) {
2262
        dict *accumulator = dictCreate(&setAccumulatorDictType,NULL);
A
antirez 已提交
2263
        dictIterator *di;
O
oranagra 已提交
2264
        dictEntry *de, *existing;
A
antirez 已提交
2265 2266 2267 2268 2269
        double score;

        if (setnum) {
            /* Our union is at least as large as the largest set.
             * Resize the dictionary ASAP to avoid useless rehashing. */
2270
            dictExpand(accumulator,zuiLength(&src[setnum-1]));
A
antirez 已提交
2271 2272 2273 2274
        }

        /* Step 1: Create a dictionary of elements -> aggregated-scores
         * by iterating one sorted set after the other. */
2275
        for (i = 0; i < setnum; i++) {
A
antirez 已提交
2276
            if (zuiLength(&src[i]) == 0) continue;
2277

2278
            zuiInitIterator(&src[i]);
2279
            while (zuiNext(&src[i],&zval)) {
A
antirez 已提交
2280
                /* Initialize value */
2281
                score = src[i].weight * zval.score;
2282
                if (isnan(score)) score = 0;
2283

A
antirez 已提交
2284
                /* Search for this element in the accumulating dictionary. */
O
oranagra 已提交
2285
                de = dictAddRaw(accumulator,zuiSdsFromValue(&zval),&existing);
A
antirez 已提交
2286
                /* If we don't have it, we need to create a new entry. */
O
oranagra 已提交
2287
                if (!existing) {
2288
                    tmp = zuiNewSdsFromValue(&zval);
A
antirez 已提交
2289 2290 2291
                    /* Remember the longest single element encountered,
                     * to understand if it's possible to convert to ziplist
                     * at the end. */
2292
                     if (sdslen(tmp) > maxelelen) maxelelen = sdslen(tmp);
O
oranagra 已提交
2293 2294
                    /* Update the element with its initial score. */
                    dictSetKey(accumulator, de, tmp);
A
antirez 已提交
2295 2296 2297 2298 2299 2300 2301 2302
                    dictSetDoubleVal(de,score);
                } else {
                    /* Update the score with the score of the new instance
                     * of the element found in the current sorted set.
                     *
                     * Here we access directly the dictEntry double
                     * value inside the union as it is a big speedup
                     * compared to using the getDouble/setDouble API. */
O
oranagra 已提交
2303
                    zunionInterAggregate(&existing->v.d,score,aggregate);
2304
                }
2305
            }
2306
            zuiClearIterator(&src[i]);
2307
        }
A
antirez 已提交
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317

        /* Step 2: convert the dictionary into the final sorted set. */
        di = dictGetIterator(accumulator);

        /* We now are aware of the final size of the resulting sorted set,
         * let's resize the dictionary embedded inside the sorted set to the
         * right size, in order to save rehashing time. */
        dictExpand(dstzset->dict,dictSize(accumulator));

        while((de = dictNext(di)) != NULL) {
2318
            sds ele = dictGetKey(de);
A
antirez 已提交
2319 2320 2321 2322 2323 2324
            score = dictGetDoubleVal(de);
            znode = zslInsert(dstzset->zsl,score,ele);
            dictAdd(dstzset->dict,ele,&znode->score);
        }
        dictReleaseIterator(di);
        dictRelease(accumulator);
2325
    } else {
A
antirez 已提交
2326
        serverPanic("Unknown operator");
2327 2328
    }

2329
    if (dbDelete(c->db,dstkey))
2330
        touched = 1;
2331
    if (dstzset->zsl->length) {
2332
        zsetConvertToZiplistIfNeeded(dstobj,maxelelen);
2333
        dbAdd(c->db,dstkey,dstobj);
2334
        addReplyLongLong(c,zsetLength(dstobj));
2335
        signalModifiedKey(c->db,dstkey);
A
antirez 已提交
2336 2337
        notifyKeyspaceEvent(NOTIFY_ZSET,
            (op == SET_OP_UNION) ? "zunionstore" : "zinterstore",
2338
            dstkey,c->db->id);
A
antirez 已提交
2339
        server.dirty++;
2340 2341
    } else {
        decrRefCount(dstobj);
2342
        addReply(c,shared.czero);
2343 2344
        if (touched) {
            signalModifiedKey(c->db,dstkey);
A
antirez 已提交
2345
            notifyKeyspaceEvent(NOTIFY_GENERIC,"del",dstkey,c->db->id);
2346 2347
            server.dirty++;
        }
2348 2349 2350 2351
    }
    zfree(src);
}

2352
void zunionstoreCommand(client *c) {
A
antirez 已提交
2353
    zunionInterGenericCommand(c,c->argv[1], SET_OP_UNION);
2354 2355
}

2356
void zinterstoreCommand(client *c) {
A
antirez 已提交
2357
    zunionInterGenericCommand(c,c->argv[1], SET_OP_INTER);
2358 2359
}

2360
void zrangeGenericCommand(client *c, int reverse) {
2361 2362 2363
    robj *key = c->argv[1];
    robj *zobj;
    int withscores = 0;
2364 2365 2366
    long start;
    long end;
    int llen;
2367
    int rangelen;
2368

2369 2370
    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != C_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != C_OK)) return;
2371 2372 2373 2374 2375 2376 2377 2378

    if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
        withscores = 1;
    } else if (c->argc >= 5) {
        addReply(c,shared.syntaxerr);
        return;
    }

2379
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
2380
         || checkType(c,zobj,OBJ_ZSET)) return;
2381

2382
    /* Sanitize indexes. */
2383
    llen = zsetLength(zobj);
2384 2385 2386 2387
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

2388 2389
    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
2390 2391 2392 2393 2394 2395 2396 2397
    if (start > end || start >= llen) {
        addReply(c,shared.emptymultibulk);
        return;
    }
    if (end >= llen) end = llen-1;
    rangelen = (end-start)+1;

    /* Return the result in form of a multi-bulk reply */
2398 2399
    addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);

2400
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

        if (reverse)
            eptr = ziplistIndex(zl,-2-(2*start));
        else
            eptr = ziplistIndex(zl,2*start);

A
antirez 已提交
2412
        serverAssertWithInfo(c,zobj,eptr != NULL);
2413 2414
        sptr = ziplistNext(zl,eptr);

2415
        while (rangelen--) {
A
antirez 已提交
2416 2417
            serverAssertWithInfo(c,zobj,eptr != NULL && sptr != NULL);
            serverAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2418 2419 2420 2421 2422
            if (vstr == NULL)
                addReplyBulkLongLong(c,vlong);
            else
                addReplyBulkCBuffer(c,vstr,vlen);

2423
            if (withscores)
2424 2425
                addReplyDouble(c,zzlGetScore(sptr));

2426 2427 2428 2429
            if (reverse)
                zzlPrev(zl,&eptr,&sptr);
            else
                zzlNext(zl,&eptr,&sptr);
2430 2431
        }

2432
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2433 2434 2435
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
2436
        sds ele;
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449

        /* Check if starting point is trivial, before doing log(N) lookup. */
        if (reverse) {
            ln = zsl->tail;
            if (start > 0)
                ln = zslGetElementByRank(zsl,llen-start);
        } else {
            ln = zsl->header->level[0].forward;
            if (start > 0)
                ln = zslGetElementByRank(zsl,start+1);
        }

        while(rangelen--) {
A
antirez 已提交
2450
            serverAssertWithInfo(c,zobj,ln != NULL);
2451 2452
            ele = ln->ele;
            addReplyBulkCBuffer(c,ele,sdslen(ele));
2453 2454 2455 2456 2457
            if (withscores)
                addReplyDouble(c,ln->score);
            ln = reverse ? ln->backward : ln->level[0].forward;
        }
    } else {
A
antirez 已提交
2458
        serverPanic("Unknown sorted set encoding");
2459 2460 2461
    }
}

2462
void zrangeCommand(client *c) {
2463 2464 2465
    zrangeGenericCommand(c,0);
}

2466
void zrevrangeCommand(client *c) {
2467 2468 2469
    zrangeGenericCommand(c,1);
}

2470
/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */
2471
void genericZrangebyscoreCommand(client *c, int reverse) {
2472
    zrangespec range;
2473
    robj *key = c->argv[1];
2474
    robj *zobj;
2475
    long offset = 0, limit = -1;
2476
    int withscores = 0;
2477 2478
    unsigned long rangelen = 0;
    void *replylen = NULL;
2479
    int minidx, maxidx;
2480

2481
    /* Parse the range arguments. */
2482 2483 2484 2485 2486 2487 2488 2489
    if (reverse) {
        /* Range is given as [max,min] */
        maxidx = 2; minidx = 3;
    } else {
        /* Range is given as [min,max] */
        minidx = 2; maxidx = 3;
    }

2490
    if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != C_OK) {
2491
        addReplyError(c,"min or max is not a float");
2492 2493
        return;
    }
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505

    /* Parse optional extra arguments. Note that ZCOUNT will exactly have
     * 4 arguments, so we'll never enter the following code path. */
    if (c->argc > 4) {
        int remaining = c->argc - 4;
        int pos = 4;

        while (remaining) {
            if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) {
                pos++; remaining--;
                withscores = 1;
            } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
2506 2507 2508 2509 2510 2511 2512
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL)
                        != C_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL)
                        != C_OK))
                {
                    return;
                }
2513 2514 2515 2516 2517 2518
                pos += 3; remaining -= 3;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }
2519
    }
2520 2521

    /* Ok, lookup the key and get the range */
2522
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2523
        checkType(c,zobj,OBJ_ZSET)) return;
2524

2525
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2526 2527 2528 2529 2530 2531
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;
        double score;
2532

2533
        /* If reversed, get the last node in range as starting point. */
2534
        if (reverse) {
2535
            eptr = zzlLastInRange(zl,&range);
2536
        } else {
2537
            eptr = zzlFirstInRange(zl,&range);
2538
        }
2539

2540 2541
        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
2542
            addReply(c, shared.emptymultibulk);
2543 2544
            return;
        }
2545

2546
        /* Get score pointer for the first element. */
A
antirez 已提交
2547
        serverAssertWithInfo(c,zobj,eptr != NULL);
2548
        sptr = ziplistNext(zl,eptr);
2549

2550 2551 2552
        /* We don't know in advance how many matching elements there are in the
         * list, so we push this object that will represent the multi-bulk
         * length in the output buffer, and will "fix" it later */
2553
        replylen = addDeferredMultiBulkLength(c);
2554 2555 2556

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2557 2558
        while (eptr && offset--) {
            if (reverse) {
2559
                zzlPrev(zl,&eptr,&sptr);
2560
            } else {
2561
                zzlNext(zl,&eptr,&sptr);
2562 2563
            }
        }
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574

        while (eptr && limit--) {
            score = zzlGetScore(sptr);

            /* Abort when the node is no longer in range. */
            if (reverse) {
                if (!zslValueGteMin(score,&range)) break;
            } else {
                if (!zslValueLteMax(score,&range)) break;
            }

2575
            /* We know the element exists, so ziplistGet should always succeed */
A
antirez 已提交
2576
            serverAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2577

2578
            rangelen++;
2579 2580 2581 2582 2583 2584 2585 2586
            if (vstr == NULL) {
                addReplyBulkLongLong(c,vlong);
            } else {
                addReplyBulkCBuffer(c,vstr,vlen);
            }

            if (withscores) {
                addReplyDouble(c,score);
2587 2588 2589
            }

            /* Move to next node */
2590
            if (reverse) {
2591
                zzlPrev(zl,&eptr,&sptr);
2592
            } else {
2593
                zzlNext(zl,&eptr,&sptr);
2594
            }
2595
        }
2596
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2597 2598 2599
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
2600

2601
        /* If reversed, get the last node in range as starting point. */
2602
        if (reverse) {
2603
            ln = zslLastInRange(zsl,&range);
2604
        } else {
2605
            ln = zslFirstInRange(zsl,&range);
2606
        }
2607 2608 2609

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
2610
            addReply(c, shared.emptymultibulk);
2611
            return;
2612 2613
        }

2614 2615 2616
        /* We don't know in advance how many matching elements there are in the
         * list, so we push this object that will represent the multi-bulk
         * length in the output buffer, and will "fix" it later */
2617
        replylen = addDeferredMultiBulkLength(c);
2618 2619 2620

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2621 2622 2623 2624 2625 2626 2627
        while (ln && offset--) {
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637

        while (ln && limit--) {
            /* Abort when the node is no longer in range. */
            if (reverse) {
                if (!zslValueGteMin(ln->score,&range)) break;
            } else {
                if (!zslValueLteMax(ln->score,&range)) break;
            }

            rangelen++;
2638
            addReplyBulkCBuffer(c,ln->ele,sdslen(ln->ele));
2639 2640 2641

            if (withscores) {
                addReplyDouble(c,ln->score);
2642 2643 2644
            }

            /* Move to next node */
2645 2646 2647 2648 2649
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
2650 2651
        }
    } else {
A
antirez 已提交
2652
        serverPanic("Unknown sorted set encoding");
2653 2654
    }

2655 2656
    if (withscores) {
        rangelen *= 2;
2657
    }
2658 2659

    setDeferredMultiBulkLength(c, replylen, rangelen);
2660 2661
}

2662
void zrangebyscoreCommand(client *c) {
2663
    genericZrangebyscoreCommand(c,0);
2664 2665
}

2666
void zrevrangebyscoreCommand(client *c) {
2667
    genericZrangebyscoreCommand(c,1);
2668 2669
}

2670
void zcountCommand(client *c) {
2671 2672 2673 2674 2675 2676
    robj *key = c->argv[1];
    robj *zobj;
    zrangespec range;
    int count = 0;

    /* Parse the range arguments */
2677
    if (zslParseRange(c->argv[2],c->argv[3],&range) != C_OK) {
2678
        addReplyError(c,"min or max is not a float");
2679 2680 2681 2682 2683
        return;
    }

    /* Lookup the sorted set */
    if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL ||
2684
        checkType(c, zobj, OBJ_ZSET)) return;
2685

2686
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2687 2688 2689 2690 2691
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        double score;

        /* Use the first element in range as the starting point */
2692
        eptr = zzlFirstInRange(zl,&range);
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702

        /* No "first" element */
        if (eptr == NULL) {
            addReply(c, shared.czero);
            return;
        }

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
        score = zzlGetScore(sptr);
A
antirez 已提交
2703
        serverAssertWithInfo(c,zobj,zslValueLteMax(score,&range));
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716

        /* Iterate over elements in range */
        while (eptr) {
            score = zzlGetScore(sptr);

            /* Abort when the node is no longer in range. */
            if (!zslValueLteMax(score,&range)) {
                break;
            } else {
                count++;
                zzlNext(zl,&eptr,&sptr);
            }
        }
2717
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2718 2719 2720 2721 2722 2723
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2724
        zn = zslFirstInRange(zsl, &range);
2725 2726 2727

        /* Use rank of first element, if any, to determine preliminary count */
        if (zn != NULL) {
2728
            rank = zslGetRank(zsl, zn->score, zn->ele);
2729 2730 2731
            count = (zsl->length - (rank - 1));

            /* Find last element in range */
2732
            zn = zslLastInRange(zsl, &range);
2733 2734 2735

            /* Use rank of last element, if any, to determine the actual count */
            if (zn != NULL) {
2736
                rank = zslGetRank(zsl, zn->score, zn->ele);
2737 2738 2739 2740
                count -= (zsl->length - rank);
            }
        }
    } else {
A
antirez 已提交
2741
        serverPanic("Unknown sorted set encoding");
A
antirez 已提交
2742 2743 2744 2745 2746
    }

    addReplyLongLong(c, count);
}

2747
void zlexcountCommand(client *c) {
A
antirez 已提交
2748 2749 2750 2751 2752 2753
    robj *key = c->argv[1];
    robj *zobj;
    zlexrangespec range;
    int count = 0;

    /* Parse the range arguments */
2754
    if (zslParseLexRange(c->argv[2],c->argv[3],&range) != C_OK) {
A
antirez 已提交
2755 2756 2757 2758 2759 2760
        addReplyError(c,"min or max not valid string range item");
        return;
    }

    /* Lookup the sorted set */
    if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL ||
2761
        checkType(c, zobj, OBJ_ZSET))
2762 2763 2764 2765
    {
        zslFreeLexRange(&range);
        return;
    }
A
antirez 已提交
2766

2767
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
A
antirez 已提交
2768 2769 2770 2771
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;

        /* Use the first element in range as the starting point */
2772
        eptr = zzlFirstInLexRange(zl,&range);
A
antirez 已提交
2773 2774 2775

        /* No "first" element */
        if (eptr == NULL) {
2776
            zslFreeLexRange(&range);
A
antirez 已提交
2777 2778 2779 2780 2781 2782
            addReply(c, shared.czero);
            return;
        }

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
A
antirez 已提交
2783
        serverAssertWithInfo(c,zobj,zzlLexValueLteMax(eptr,&range));
A
antirez 已提交
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794

        /* Iterate over elements in range */
        while (eptr) {
            /* Abort when the node is no longer in range. */
            if (!zzlLexValueLteMax(eptr,&range)) {
                break;
            } else {
                count++;
                zzlNext(zl,&eptr,&sptr);
            }
        }
2795
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
2796 2797 2798 2799 2800 2801
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2802
        zn = zslFirstInLexRange(zsl, &range);
A
antirez 已提交
2803 2804 2805

        /* Use rank of first element, if any, to determine preliminary count */
        if (zn != NULL) {
2806
            rank = zslGetRank(zsl, zn->score, zn->ele);
A
antirez 已提交
2807 2808 2809
            count = (zsl->length - (rank - 1));

            /* Find last element in range */
2810
            zn = zslLastInLexRange(zsl, &range);
A
antirez 已提交
2811 2812 2813

            /* Use rank of last element, if any, to determine the actual count */
            if (zn != NULL) {
2814
                rank = zslGetRank(zsl, zn->score, zn->ele);
A
antirez 已提交
2815 2816 2817 2818
                count -= (zsl->length - rank);
            }
        }
    } else {
A
antirez 已提交
2819
        serverPanic("Unknown sorted set encoding");
2820 2821
    }

2822
    zslFreeLexRange(&range);
2823
    addReplyLongLong(c, count);
2824 2825
}

2826
/* This command implements ZRANGEBYLEX, ZREVRANGEBYLEX. */
2827
void genericZrangebylexCommand(client *c, int reverse) {
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
    zlexrangespec range;
    robj *key = c->argv[1];
    robj *zobj;
    long offset = 0, limit = -1;
    unsigned long rangelen = 0;
    void *replylen = NULL;
    int minidx, maxidx;

    /* Parse the range arguments. */
    if (reverse) {
        /* Range is given as [max,min] */
        maxidx = 2; minidx = 3;
    } else {
        /* Range is given as [min,max] */
        minidx = 2; maxidx = 3;
    }

2845
    if (zslParseLexRange(c->argv[minidx],c->argv[maxidx],&range) != C_OK) {
2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
        addReplyError(c,"min or max not valid string range item");
        return;
    }

    /* Parse optional extra arguments. Note that ZCOUNT will exactly have
     * 4 arguments, so we'll never enter the following code path. */
    if (c->argc > 4) {
        int remaining = c->argc - 4;
        int pos = 4;

        while (remaining) {
            if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
2858 2859
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != C_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != C_OK)) return;
2860 2861
                pos += 3; remaining -= 3;
            } else {
2862
                zslFreeLexRange(&range);
2863 2864 2865 2866 2867 2868 2869 2870
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* Ok, lookup the key and get the range */
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2871
        checkType(c,zobj,OBJ_ZSET))
2872 2873 2874 2875
    {
        zslFreeLexRange(&range);
        return;
    }
2876

2877
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2878 2879 2880 2881 2882 2883 2884 2885
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2886
            eptr = zzlLastInLexRange(zl,&range);
2887
        } else {
2888
            eptr = zzlFirstInLexRange(zl,&range);
2889 2890 2891 2892 2893
        }

        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
            addReply(c, shared.emptymultibulk);
2894
            zslFreeLexRange(&range);
2895 2896 2897 2898
            return;
        }

        /* Get score pointer for the first element. */
A
antirez 已提交
2899
        serverAssertWithInfo(c,zobj,eptr != NULL);
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
        sptr = ziplistNext(zl,eptr);

        /* We don't know in advance how many matching elements there are in the
         * list, so we push this object that will represent the multi-bulk
         * length in the output buffer, and will "fix" it later */
        replylen = addDeferredMultiBulkLength(c);

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
        while (eptr && offset--) {
            if (reverse) {
                zzlPrev(zl,&eptr,&sptr);
            } else {
                zzlNext(zl,&eptr,&sptr);
            }
        }

        while (eptr && limit--) {
            /* Abort when the node is no longer in range. */
            if (reverse) {
                if (!zzlLexValueGteMin(eptr,&range)) break;
            } else {
                if (!zzlLexValueLteMax(eptr,&range)) break;
            }

            /* We know the element exists, so ziplistGet should always
             * succeed. */
A
antirez 已提交
2927
            serverAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942

            rangelen++;
            if (vstr == NULL) {
                addReplyBulkLongLong(c,vlong);
            } else {
                addReplyBulkCBuffer(c,vstr,vlen);
            }

            /* Move to next node */
            if (reverse) {
                zzlPrev(zl,&eptr,&sptr);
            } else {
                zzlNext(zl,&eptr,&sptr);
            }
        }
2943
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2944 2945 2946 2947 2948 2949
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2950
            ln = zslLastInLexRange(zsl,&range);
2951
        } else {
2952
            ln = zslFirstInLexRange(zsl,&range);
2953 2954 2955 2956 2957
        }

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
            addReply(c, shared.emptymultibulk);
2958
            zslFreeLexRange(&range);
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
            return;
        }

        /* We don't know in advance how many matching elements there are in the
         * list, so we push this object that will represent the multi-bulk
         * length in the output buffer, and will "fix" it later */
        replylen = addDeferredMultiBulkLength(c);

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
        while (ln && offset--) {
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }

        while (ln && limit--) {
            /* Abort when the node is no longer in range. */
            if (reverse) {
2980
                if (!zslLexValueGteMin(ln->ele,&range)) break;
2981
            } else {
2982
                if (!zslLexValueLteMax(ln->ele,&range)) break;
2983 2984 2985
            }

            rangelen++;
2986
            addReplyBulkCBuffer(c,ln->ele,sdslen(ln->ele));
2987 2988 2989 2990 2991 2992 2993 2994 2995

            /* Move to next node */
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
    } else {
A
antirez 已提交
2996
        serverPanic("Unknown sorted set encoding");
2997 2998
    }

2999
    zslFreeLexRange(&range);
3000 3001 3002
    setDeferredMultiBulkLength(c, replylen, rangelen);
}

3003
void zrangebylexCommand(client *c) {
3004 3005 3006
    genericZrangebylexCommand(c,0);
}

3007
void zrevrangebylexCommand(client *c) {
3008 3009 3010
    genericZrangebylexCommand(c,1);
}

3011
void zcardCommand(client *c) {
3012 3013
    robj *key = c->argv[1];
    robj *zobj;
3014

3015
    if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL ||
3016
        checkType(c,zobj,OBJ_ZSET)) return;
3017

3018
    addReplyLongLong(c,zsetLength(zobj));
3019 3020
}

3021
void zscoreCommand(client *c) {
3022 3023 3024
    robj *key = c->argv[1];
    robj *zobj;
    double score;
3025

3026
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
3027
        checkType(c,zobj,OBJ_ZSET)) return;
3028

3029
    if (zsetScore(zobj,c->argv[2]->ptr,&score) == C_ERR) {
A
antirez 已提交
3030
        addReply(c,shared.nullbulk);
3031
    } else {
A
antirez 已提交
3032
        addReplyDouble(c,score);
3033 3034 3035
    }
}

3036
void zrankGenericCommand(client *c, int reverse) {
3037 3038 3039
    robj *key = c->argv[1];
    robj *ele = c->argv[2];
    robj *zobj;
A
antirez 已提交
3040
    long rank;
3041

3042
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
3043
        checkType(c,zobj,OBJ_ZSET)) return;
3044

A
antirez 已提交
3045
    serverAssertWithInfo(c,ele,sdsEncodedObject(ele));
A
antirez 已提交
3046 3047 3048
    rank = zsetRank(zobj,ele->ptr,reverse);
    if (rank >= 0) {
        addReplyLongLong(c,rank);
3049
    } else {
A
antirez 已提交
3050
        addReply(c,shared.nullbulk);
3051 3052 3053
    }
}

3054
void zrankCommand(client *c) {
3055 3056 3057
    zrankGenericCommand(c, 0);
}

3058
void zrevrankCommand(client *c) {
3059 3060
    zrankGenericCommand(c, 1);
}
A
antirez 已提交
3061

3062
void zscanCommand(client *c) {
A
antirez 已提交
3063
    robj *o;
3064
    unsigned long cursor;
A
antirez 已提交
3065

3066
    if (parseScanCursorOrReply(c,c->argv[2],&cursor) == C_ERR) return;
3067
    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL ||
3068
        checkType(c,o,OBJ_ZSET)) return;
3069
    scanGenericCommand(c,o,cursor);
A
antirez 已提交
3070
}