t_zset.c 90.2 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 41 42 43 44 45
 * At the same time the elements are added to a skip list mapping scores
 * to Redis objects (so objects are sorted by scores in this "view"). */

/* This skiplist implementation is almost a C translation of the original
 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
 * Alternative to Balanced Trees", modified in three ways:
A
antirez 已提交
46
 * a) this implementation allows for repeated scores.
47 48 49 50 51
 * 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. */

52 53 54
#include "redis.h"
#include <math.h>

A
antirez 已提交
55 56 57
static int zslLexValueGteMin(robj *value, zlexrangespec *spec);
static int zslLexValueLteMax(robj *value, zlexrangespec *spec);

58
zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
59
    zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
60 61 62 63 64 65 66 67 68 69 70 71 72 73
    zn->score = score;
    zn->obj = obj;
    return zn;
}

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++) {
74 75
        zsl->header->level[j].forward = NULL;
        zsl->header->level[j].span = 0;
76 77 78 79 80 81 82 83 84 85 86 87
    }
    zsl->header->backward = NULL;
    zsl->tail = NULL;
    return zsl;
}

void zslFreeNode(zskiplistNode *node) {
    decrRefCount(node->obj);
    zfree(node);
}

void zslFree(zskiplist *zsl) {
88
    zskiplistNode *node = zsl->header->level[0].forward, *next;
89 90 91

    zfree(zsl->header);
    while(node) {
92
        next = node->level[0].forward;
93 94 95 96 97 98
        zslFreeNode(node);
        node = next;
    }
    zfree(zsl);
}

99 100 101 102
/* 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. */
103 104 105 106 107 108 109
int zslRandomLevel(void) {
    int level = 1;
    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
        level += 1;
    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}

110
zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
111 112 113 114
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned int rank[ZSKIPLIST_MAXLEVEL];
    int i, level;

115
    redisAssert(!isnan(score));
116 117 118 119
    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];
120 121 122 123 124 125
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,obj) < 0))) {
            rank[i] += x->level[i].span;
            x = x->level[i].forward;
126 127 128 129 130
        }
        update[i] = x;
    }
    /* we assume the key is not already inside, since we allow duplicated
     * scores, and the re-insertion of score and redis object should never
G
guiquanz 已提交
131
     * happen since the caller of zslInsert() should test in the hash table
132 133 134 135 136 137
     * if the element is already inside or not. */
    level = zslRandomLevel();
    if (level > zsl->level) {
        for (i = zsl->level; i < level; i++) {
            rank[i] = 0;
            update[i] = zsl->header;
138
            update[i]->level[i].span = zsl->length;
139 140 141 142 143
        }
        zsl->level = level;
    }
    x = zslCreateNode(level,score,obj);
    for (i = 0; i < level; i++) {
144 145
        x->level[i].forward = update[i]->level[i].forward;
        update[i]->level[i].forward = x;
146 147

        /* update span covered by update[i] as x is inserted here */
148 149
        x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
        update[i]->level[i].span = (rank[0] - rank[i]) + 1;
150 151 152 153
    }

    /* increment span for untouched levels */
    for (i = level; i < zsl->level; i++) {
154
        update[i]->level[i].span++;
155 156 157
    }

    x->backward = (update[0] == zsl->header) ? NULL : update[0];
158 159
    if (x->level[0].forward)
        x->level[0].forward->backward = x;
160 161 162
    else
        zsl->tail = x;
    zsl->length++;
163
    return x;
164 165 166 167 168 169
}

/* 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++) {
170 171 172
        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;
173
        } else {
174
            update[i]->level[i].span -= 1;
175 176
        }
    }
177 178
    if (x->level[0].forward) {
        x->level[0].forward->backward = x->backward;
179 180 181
    } else {
        zsl->tail = x->backward;
    }
182
    while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
183 184 185 186 187 188 189 190 191 192 193
        zsl->level--;
    zsl->length--;
}

/* Delete an element with matching score/object from the skiplist. */
int zslDelete(zskiplist *zsl, double score, robj *obj) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
194 195 196 197 198
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,obj) < 0)))
            x = x->level[i].forward;
199 200 201 202
        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. */
203
    x = x->level[0].forward;
204 205 206 207 208 209 210 211 212 213
    if (x && score == x->score && equalStringObjects(x->obj,obj)) {
        zslDeleteNode(zsl, x, update);
        zslFreeNode(x);
        return 1;
    } else {
        return 0; /* not found */
    }
    return 0; /* not found */
}

P
Pieter Noordhuis 已提交
214
static int zslValueGteMin(double value, zrangespec *spec) {
215 216 217
    return spec->minex ? (value > spec->min) : (value >= spec->min);
}

P
Pieter Noordhuis 已提交
218
static int zslValueLteMax(double value, zrangespec *spec) {
219 220 221 222 223 224 225
    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;

226 227 228 229
    /* Test for ranges that will always be empty. */
    if (range->min > range->max ||
            (range->min == range->max && (range->minex || range->maxex)))
        return 0;
230
    x = zsl->tail;
P
Pieter Noordhuis 已提交
231
    if (x == NULL || !zslValueGteMin(x->score,range))
232 233
        return 0;
    x = zsl->header->level[0].forward;
P
Pieter Noordhuis 已提交
234
    if (x == NULL || !zslValueLteMax(x->score,range))
235 236 237 238 239 240
        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. */
241
zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) {
242 243 244 245
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
246
    if (!zslIsInRange(zsl,range)) return NULL;
247 248 249 250 251

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

256
    /* This is an inner range, so the next node cannot be NULL. */
257
    x = x->level[0].forward;
258 259 260
    redisAssert(x != NULL);

    /* Check if score <= max. */
261
    if (!zslValueLteMax(x->score,range)) return NULL;
262 263 264 265 266
    return x;
}

/* Find the last node that is contained in the specified range.
 * Returns NULL when no element is contained in the range. */
267
zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) {
268 269 270 271
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
272
    if (!zslIsInRange(zsl,range)) return NULL;
273 274 275 276 277

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *IN* range. */
        while (x->level[i].forward &&
278
            zslValueLteMax(x->level[i].forward->score,range))
279 280 281
                x = x->level[i].forward;
    }

282 283 284 285
    /* This is an inner range, so this node cannot be NULL. */
    redisAssert(x != NULL);

    /* Check if score >= min. */
286
    if (!zslValueGteMin(x->score,range)) return NULL;
287 288 289
    return x;
}

290
/* Delete all the elements with score between min and max from the skiplist.
G
guiquanz 已提交
291
 * Min and max are inclusive, so a score >= min || score <= max is deleted.
292 293
 * 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. */
294
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) {
295 296 297 298 299 300
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
301 302 303
        while (x->level[i].forward && (range->minex ?
            x->level[i].forward->score <= range->min :
            x->level[i].forward->score < range->min))
304
                x = x->level[i].forward;
305 306
        update[i] = x;
    }
307 308

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

    /* Delete nodes while in range. */
312 313 314
    while (x &&
           (range->maxex ? x->score < range->max : x->score <= range->max))
    {
315
        zskiplistNode *next = x->level[0].forward;
316
        zslDeleteNode(zsl,x,update);
317 318 319 320 321
        dictDelete(dict,x->obj);
        zslFreeNode(x);
        removed++;
        x = next;
    }
322
    return removed;
323 324
}

A
antirez 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
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 &&
            !zslLexValueGteMin(x->level[i].forward->obj,range))
                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. */
    while (x && zslLexValueLteMax(x->obj,range)) {
        zskiplistNode *next = x->level[0].forward;
        zslDeleteNode(zsl,x,update);
        dictDelete(dict,x->obj);
        zslFreeNode(x);
        removed++;
        x = next;
    }
    return removed;
}

354 355 356 357 358 359 360 361 362
/* 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--) {
363 364 365
        while (x->level[i].forward && (traversed + x->level[i].span) < start) {
            traversed += x->level[i].span;
            x = x->level[i].forward;
366 367 368 369 370
        }
        update[i] = x;
    }

    traversed++;
371
    x = x->level[0].forward;
372
    while (x && traversed <= end) {
373
        zskiplistNode *next = x->level[0].forward;
374
        zslDeleteNode(zsl,x,update);
375 376 377 378 379 380 381 382 383 384 385 386 387
        dictDelete(dict,x->obj);
        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. */
388
unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
389 390 391 392 393 394
    zskiplistNode *x;
    unsigned long rank = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
395 396 397 398 399 400
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,o) <= 0))) {
            rank += x->level[i].span;
            x = x->level[i].forward;
401 402 403 404 405 406 407 408 409 410 411
        }

        /* x might be equal to zsl->header, so test if obj is non-NULL */
        if (x->obj && equalStringObjects(x->obj,o)) {
            return rank;
        }
    }
    return 0;
}

/* Finds an element by its rank. The rank argument needs to be 1-based. */
412
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
413 414 415 416 417 418
    zskiplistNode *x;
    unsigned long traversed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
419
        while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
420
        {
421 422
            traversed += x->level[i].span;
            x = x->level[i].forward;
423 424 425 426 427 428 429 430
        }
        if (traversed == rank) {
            return x;
        }
    }
    return NULL;
}

431
/* Populate the rangespec according to the objects min and max. */
432 433
static int zslParseRange(robj *min, robj *max, zrangespec *spec) {
    char *eptr;
434 435 436 437 438 439 440 441 442 443
    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 */
    if (min->encoding == REDIS_ENCODING_INT) {
        spec->min = (long)min->ptr;
    } else {
        if (((char*)min->ptr)[0] == '(') {
444 445
            spec->min = strtod((char*)min->ptr+1,&eptr);
            if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
446 447
            spec->minex = 1;
        } else {
448 449
            spec->min = strtod((char*)min->ptr,&eptr);
            if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
450 451 452 453 454 455
        }
    }
    if (max->encoding == REDIS_ENCODING_INT) {
        spec->max = (long)max->ptr;
    } else {
        if (((char*)max->ptr)[0] == '(') {
456 457
            spec->max = strtod((char*)max->ptr+1,&eptr);
            if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
458 459
            spec->maxex = 1;
        } else {
460 461
            spec->max = strtod((char*)max->ptr,&eptr);
            if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
462 463 464 465 466 467
        }
    }

    return REDIS_OK;
}

468 469 470 471 472 473 474 475 476 477 478 479 480
/* ------------------------ 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
  * respectively if the item is exclusive or inclusive. REDIS_OK will be
  * returned.
  *
481
  * If the string is not a valid range REDIS_ERR is returned, and the value
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
  * of *dest and *ex is undefined. */
int zslParseLexRangeItem(robj *item, robj **dest, int *ex) {
    char *c = item->ptr;

    switch(c[0]) {
    case '+':
        if (c[1] != '\0') return REDIS_ERR;
        *ex = 0;
        *dest = shared.maxstring;
        incrRefCount(shared.maxstring);
        return REDIS_OK;
    case '-':
        if (c[1] != '\0') return REDIS_ERR;
        *ex = 0;
        *dest = shared.minstring;
        incrRefCount(shared.minstring);
        return REDIS_OK;
    case '(':
        *ex = 1;
        *dest = createStringObject(c+1,sdslen(c)-1);
        return REDIS_OK;
    case '[':
        *ex = 0;
        *dest = createStringObject(c+1,sdslen(c)-1);
        return REDIS_OK;
    default:
        return REDIS_ERR;
    }
}

512 513 514 515 516
/* Populate the rangespec according to the objects min and max.
 *
 * Return REDIS_OK on success. On error REDIS_ERR is returned.
 * When OK is returned the structure must be freed with zslFreeLexRange(),
 * otherwise no release is needed. */
517
static int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec) {
518 519
    /* The range can't be valid if objects are integer encoded.
     * Every item must start with ( or [. */
520 521 522 523 524 525 526 527 528 529 530 531 532 533
    if (min->encoding == REDIS_ENCODING_INT ||
        max->encoding == REDIS_ENCODING_INT) return REDIS_ERR;

    spec->min = spec->max = NULL;
    if (zslParseLexRangeItem(min, &spec->min, &spec->minex) == REDIS_ERR ||
        zslParseLexRangeItem(max, &spec->max, &spec->maxex) == REDIS_ERR) {
        if (spec->min) decrRefCount(spec->min);
        if (spec->max) decrRefCount(spec->max);
        return REDIS_ERR;
    } else {
        return REDIS_OK;
    }
}

534 535 536 537 538 539 540
/* Free a lex range structure, must be called only after zelParseLexRange()
 * populated the structure with success (REDIS_OK returned). */
void zslFreeLexRange(zlexrangespec *spec) {
    decrRefCount(spec->min);
    decrRefCount(spec->max);
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
/* This is just a wrapper to compareStringObjects() that is able to
 * handle shared.minstring and shared.maxstring as the equivalent of
 * -inf and +inf for strings */
int compareStringObjectsForLexRange(robj *a, robj *b) {
    if (a == b) return 0; /* This makes sure that we handle inf,inf and
                             -inf,-inf ASAP. One special case less. */
    if (a == shared.minstring || b == shared.maxstring) return -1;
    if (a == shared.maxstring || b == shared.minstring) return 1;
    return compareStringObjects(a,b);
}

static int zslLexValueGteMin(robj *value, zlexrangespec *spec) {
    return spec->minex ?
        (compareStringObjectsForLexRange(value,spec->min) > 0) :
        (compareStringObjectsForLexRange(value,spec->min) >= 0);
}

static int zslLexValueLteMax(robj *value, zlexrangespec *spec) {
    return spec->maxex ?
        (compareStringObjectsForLexRange(value,spec->max) < 0) :
        (compareStringObjectsForLexRange(value,spec->max) <= 0);
}

/* 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. */
    if (compareStringObjectsForLexRange(range->min,range->max) > 1 ||
            (compareStringObjects(range->min,range->max) == 0 &&
            (range->minex || range->maxex)))
        return 0;
    x = zsl->tail;
    if (x == NULL || !zslLexValueGteMin(x->obj,range))
        return 0;
    x = zsl->header->level[0].forward;
    if (x == NULL || !zslLexValueLteMax(x->obj,range))
        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. */
584
zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range) {
585 586 587 588
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
589
    if (!zslIsInLexRange(zsl,range)) return NULL;
590 591 592 593 594

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *OUT* of range. */
        while (x->level[i].forward &&
595
            !zslLexValueGteMin(x->level[i].forward->obj,range))
596 597 598 599 600 601 602 603
                x = x->level[i].forward;
    }

    /* This is an inner range, so the next node cannot be NULL. */
    x = x->level[0].forward;
    redisAssert(x != NULL);

    /* Check if score <= max. */
604
    if (!zslLexValueLteMax(x->obj,range)) return NULL;
605 606 607 608 609
    return x;
}

/* Find the last node that is contained in the specified range.
 * Returns NULL when no element is contained in the range. */
610
zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range) {
611 612 613 614
    zskiplistNode *x;
    int i;

    /* If everything is out of range, return early. */
615
    if (!zslIsInLexRange(zsl,range)) return NULL;
616 617 618 619 620

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *IN* range. */
        while (x->level[i].forward &&
621
            zslLexValueLteMax(x->level[i].forward->obj,range))
622 623 624 625 626 627 628
                x = x->level[i].forward;
    }

    /* This is an inner range, so this node cannot be NULL. */
    redisAssert(x != NULL);

    /* Check if score >= min. */
629
    if (!zslLexValueGteMin(x->obj,range)) return NULL;
630 631 632
    return x;
}

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
/*-----------------------------------------------------------------------------
 * Ziplist-backed sorted set API
 *----------------------------------------------------------------------------*/

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

    redisAssert(sptr != NULL);
    redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));

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

    return score;
}

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
/* Return a ziplist element as a Redis string object.
 * This simple abstraction can be used to simplifies some code at the
 * cost of some performance. */
robj *ziplistGetObject(unsigned char *sptr) {
    unsigned char *vstr;
    unsigned int vlen;
    long long vlong;

    redisAssert(sptr != NULL);
    redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));

    if (vstr) {
        return createStringObject((char*)vstr,vlen);
    } else {
        return createStringObjectFromLongLong(vlong);
    }
}

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
/* 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;

    redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
    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;
}

697
unsigned int zzlLength(unsigned char *zl) {
P
Pieter Noordhuis 已提交
698 699 700
    return ziplistLen(zl)/2;
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
/* 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;
    redisAssert(*eptr != NULL && *sptr != NULL);

    _eptr = ziplistNext(zl,*sptr);
    if (_eptr != NULL) {
        _sptr = ziplistNext(zl,_eptr);
        redisAssert(_sptr != NULL);
    } 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;
    redisAssert(*eptr != NULL && *sptr != NULL);

    _sptr = ziplistPrev(zl,*eptr);
    if (_sptr != NULL) {
        _eptr = ziplistPrev(zl,_sptr);
        redisAssert(_eptr != NULL);
    } else {
        /* No previous entry. */
        _eptr = NULL;
    }

    *eptr = _eptr;
    *sptr = _sptr;
}

739 740 741 742 743 744 745 746 747 748 749 750
/* 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. */
751
    if (p == NULL) return 0; /* Empty sorted set */
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
    score = zzlGetScore(p);
    if (!zslValueGteMin(score,range))
        return 0;

    p = ziplistIndex(zl,1); /* First score. */
    redisAssert(p != NULL);
    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. */
767
unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range) {
768 769 770 771
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;
    double score;

    /* If everything is out of range, return early. */
772
    if (!zzlIsInRange(zl,range)) return NULL;
773 774 775 776 777 778

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
        redisAssert(sptr != NULL);

        score = zzlGetScore(sptr);
779
        if (zslValueGteMin(score,range)) {
780
            /* Check if score <= max. */
781
            if (zslValueLteMax(score,range))
782 783 784
                return eptr;
            return NULL;
        }
785 786 787 788 789 790 791 792 793 794

        /* 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. */
795
unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range) {
796 797 798 799
    unsigned char *eptr = ziplistIndex(zl,-2), *sptr;
    double score;

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

    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
        redisAssert(sptr != NULL);

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

        /* 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)
            redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
        else
            eptr = NULL;
    }

    return NULL;
}

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
static int zzlLexValueGteMin(unsigned char *p, zlexrangespec *spec) {
    robj *value = ziplistGetObject(p);
    int res = zslLexValueGteMin(value,spec);
    decrRefCount(value);
    return res;
}

static int zzlLexValueLteMax(unsigned char *p, zlexrangespec *spec) {
    robj *value = ziplistGetObject(p);
    int res = zslLexValueLteMax(value,spec);
    decrRefCount(value);
    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. */
    if (compareStringObjectsForLexRange(range->min,range->max) > 1 ||
            (compareStringObjects(range->min,range->max) == 0 &&
            (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. */
    redisAssert(p != NULL);
    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. */
866
unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range) {
867 868 869
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;

    /* If everything is out of range, return early. */
870
    if (!zzlIsInLexRange(zl,range)) return NULL;
871 872

    while (eptr != NULL) {
873
        if (zzlLexValueGteMin(eptr,range)) {
874
            /* Check if score <= max. */
875
            if (zzlLexValueLteMax(eptr,range))
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
                return eptr;
            return NULL;
        }

        /* Move to next element. */
        sptr = ziplistNext(zl,eptr); /* This element score. Skip it. */
        redisAssert(sptr != NULL);
        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. */
891
unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range) {
892 893 894
    unsigned char *eptr = ziplistIndex(zl,-2), *sptr;

    /* If everything is out of range, return early. */
895
    if (!zzlIsInLexRange(zl,range)) return NULL;
896 897

    while (eptr != NULL) {
898
        if (zzlLexValueLteMax(eptr,range)) {
899
            /* Check if score >= min. */
900
            if (zzlLexValueGteMin(eptr,range))
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
                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)
            redisAssert((eptr = ziplistPrev(zl,sptr)) != NULL);
        else
            eptr = NULL;
    }

    return NULL;
}

917
unsigned char *zzlFind(unsigned char *zl, robj *ele, double *score) {
918 919 920 921 922
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;

    ele = getDecodedObject(ele);
    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
923
        redisAssertWithInfo(NULL,ele,sptr != NULL);
924 925 926

        if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) {
            /* Matching element, pull out score. */
P
Pieter Noordhuis 已提交
927
            if (score != NULL) *score = zzlGetScore(sptr);
928 929 930 931 932 933 934 935 936 937 938 939 940 941
            decrRefCount(ele);
            return eptr;
        }

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

    decrRefCount(ele);
    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. */
942
unsigned char *zzlDelete(unsigned char *zl, unsigned char *eptr) {
943 944 945 946 947
    unsigned char *p = eptr;

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

951
unsigned char *zzlInsertAt(unsigned char *zl, unsigned char *eptr, robj *ele, double score) {
952 953 954
    unsigned char *sptr;
    char scorebuf[128];
    int scorelen;
P
Pieter Noordhuis 已提交
955
    size_t offset;
956

957
    redisAssertWithInfo(NULL,ele,sdsEncodedObject(ele));
958 959 960 961 962 963 964 965 966 967 968
    scorelen = d2string(scorebuf,sizeof(scorebuf),score);
    if (eptr == NULL) {
        zl = ziplistPush(zl,ele->ptr,sdslen(ele->ptr),ZIPLIST_TAIL);
        zl = ziplistPush(zl,(unsigned char*)scorebuf,scorelen,ZIPLIST_TAIL);
    } else {
        /* Keep offset relative to zl, as it might be re-allocated. */
        offset = eptr-zl;
        zl = ziplistInsert(zl,eptr,ele->ptr,sdslen(ele->ptr));
        eptr = zl+offset;

        /* Insert score after the element. */
969
        redisAssertWithInfo(NULL,ele,(sptr = ziplistNext(zl,eptr)) != NULL);
970 971 972
        zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen);
    }

973
    return zl;
974 975 976 977
}

/* Insert (element,score) pair in ziplist. This function assumes the element is
 * not yet present in the list. */
978
unsigned char *zzlInsert(unsigned char *zl, robj *ele, double score) {
979 980 981 982 983 984
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;
    double s;

    ele = getDecodedObject(ele);
    while (eptr != NULL) {
        sptr = ziplistNext(zl,eptr);
985
        redisAssertWithInfo(NULL,ele,sptr != NULL);
986 987 988 989 990 991
        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. */
992
            zl = zzlInsertAt(zl,eptr,ele,score);
993
            break;
P
Pieter Noordhuis 已提交
994 995
        } else if (s == score) {
            /* Ensure lexicographical ordering for elements. */
996
            if (zzlCompareElements(eptr,ele->ptr,sdslen(ele->ptr)) > 0) {
997
                zl = zzlInsertAt(zl,eptr,ele,score);
P
Pieter Noordhuis 已提交
998 999
                break;
            }
1000 1001 1002 1003 1004 1005 1006
        }

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

    /* Push on tail of list when it was not yet inserted. */
P
Pieter Noordhuis 已提交
1007
    if (eptr == NULL)
1008
        zl = zzlInsertAt(zl,NULL,ele,score);
1009 1010

    decrRefCount(ele);
1011
    return zl;
1012
}
1013

1014
unsigned char *zzlDeleteRangeByScore(unsigned char *zl, zrangespec *range, unsigned long *deleted) {
1015 1016
    unsigned char *eptr, *sptr;
    double score;
1017
    unsigned long num = 0;
1018

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

1021 1022
    eptr = zzlFirstInRange(zl,range);
    if (eptr == NULL) return zl;
1023 1024 1025 1026 1027

    /* 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);
1028
        if (zslValueLteMax(score,range)) {
1029 1030 1031
            /* Delete both the element and the score. */
            zl = ziplistDelete(zl,&eptr);
            zl = ziplistDelete(zl,&eptr);
1032
            num++;
1033 1034 1035 1036 1037 1038
        } else {
            /* No longer in range. */
            break;
        }
    }

1039 1040
    if (deleted != NULL) *deleted = num;
    return zl;
1041 1042
}

A
antirez 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
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;
}

1070 1071
/* 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 */
1072
unsigned char *zzlDeleteRangeByRank(unsigned char *zl, unsigned int start, unsigned int end, unsigned long *deleted) {
1073
    unsigned int num = (end-start)+1;
1074 1075 1076
    if (deleted) *deleted = num;
    zl = ziplistDeleteRange(zl,2*(start-1),2*num);
    return zl;
1077 1078
}

1079 1080 1081 1082
/*-----------------------------------------------------------------------------
 * Common sorted set API
 *----------------------------------------------------------------------------*/

1083
unsigned int zsetLength(robj *zobj) {
1084 1085
    int length = -1;
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1086
        length = zzlLength(zobj->ptr);
1087
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
1088 1089 1090 1091 1092 1093 1094
        length = ((zset*)zobj->ptr)->zsl->length;
    } else {
        redisPanic("Unknown sorted set encoding");
    }
    return length;
}

1095
void zsetConvert(robj *zobj, int encoding) {
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    zset *zs;
    zskiplistNode *node, *next;
    robj *ele;
    double score;

    if (zobj->encoding == encoding) return;
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

1109
        if (encoding != REDIS_ENCODING_SKIPLIST)
1110 1111 1112 1113 1114 1115 1116
            redisPanic("Unknown target encoding");

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

        eptr = ziplistIndex(zl,0);
1117
        redisAssertWithInfo(NULL,zobj,eptr != NULL);
1118
        sptr = ziplistNext(zl,eptr);
1119
        redisAssertWithInfo(NULL,zobj,sptr != NULL);
1120 1121 1122

        while (eptr != NULL) {
            score = zzlGetScore(sptr);
1123
            redisAssertWithInfo(NULL,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
1124 1125 1126 1127 1128 1129 1130
            if (vstr == NULL)
                ele = createStringObjectFromLongLong(vlong);
            else
                ele = createStringObject((char*)vstr,vlen);

            /* Has incremented refcount since it was just created. */
            node = zslInsert(zs->zsl,score,ele);
1131
            redisAssertWithInfo(NULL,zobj,dictAdd(zs->dict,ele,&node->score) == DICT_OK);
1132 1133 1134 1135 1136 1137
            incrRefCount(ele); /* Added to dictionary. */
            zzlNext(zl,&eptr,&sptr);
        }

        zfree(zobj->ptr);
        zobj->ptr = zs;
1138 1139
        zobj->encoding = REDIS_ENCODING_SKIPLIST;
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
        unsigned char *zl = ziplistNew();

        if (encoding != REDIS_ENCODING_ZIPLIST)
            redisPanic("Unknown target encoding");

        /* 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) {
            ele = getDecodedObject(node->obj);
1155
            zl = zzlInsertAt(zl,NULL,ele,node->score);
1156 1157 1158 1159 1160 1161 1162 1163
            decrRefCount(ele);

            next = node->level[0].forward;
            zslFreeNode(node);
            node = next;
        }

        zfree(zs);
1164
        zobj->ptr = zl;
1165 1166 1167 1168 1169 1170
        zobj->encoding = REDIS_ENCODING_ZIPLIST;
    } else {
        redisPanic("Unknown sorted set encoding");
    }
}

1171 1172 1173 1174
/*-----------------------------------------------------------------------------
 * Sorted set commands 
 *----------------------------------------------------------------------------*/

1175
/* This generic command implements both ZADD and ZINCRBY. */
1176
void zaddGenericCommand(redisClient *c, int incr) {
1177
    static char *nanerr = "resulting score is not a number (NaN)";
1178 1179
    robj *key = c->argv[1];
    robj *ele;
1180 1181
    robj *zobj;
    robj *curobj;
1182
    double score = 0, *scores = NULL, curscore = 0.0;
A
antirez 已提交
1183
    int j, elements = (c->argc-2)/2;
1184
    int added = 0, updated = 0;
1185

A
antirez 已提交
1186 1187
    if (c->argc % 2) {
        addReply(c,shared.syntaxerr);
1188
        return;
A
antirez 已提交
1189 1190 1191 1192 1193 1194 1195 1196
    }

    /* 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++) {
        if (getDoubleFromObjectOrReply(c,c->argv[2+j*2],&scores[j],NULL)
1197
            != REDIS_OK) goto cleanup;
A
antirez 已提交
1198
    }
1199

A
antirez 已提交
1200
    /* Lookup the key and create the sorted set if does not exist. */
1201 1202
    zobj = lookupKeyWrite(c->db,key);
    if (zobj == NULL) {
1203 1204 1205 1206 1207 1208 1209
        if (server.zset_max_ziplist_entries == 0 ||
            server.zset_max_ziplist_value < sdslen(c->argv[3]->ptr))
        {
            zobj = createZsetObject();
        } else {
            zobj = createZsetZiplistObject();
        }
1210
        dbAdd(c->db,key,zobj);
1211
    } else {
1212
        if (zobj->type != REDIS_ZSET) {
1213
            addReply(c,shared.wrongtypeerr);
1214
            goto cleanup;
1215 1216 1217
        }
    }

A
antirez 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    for (j = 0; j < elements; j++) {
        score = scores[j];

        if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
            unsigned char *eptr;

            /* Prefer non-encoded element when dealing with ziplists. */
            ele = c->argv[3+j*2];
            if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
                if (incr) {
                    score += curscore;
                    if (isnan(score)) {
                        addReplyError(c,nanerr);
1231
                        goto cleanup;
A
antirez 已提交
1232
                    }
1233 1234
                }

A
antirez 已提交
1235 1236 1237 1238 1239
                /* Remove and re-insert when score changed. */
                if (score != curscore) {
                    zobj->ptr = zzlDelete(zobj->ptr,eptr);
                    zobj->ptr = zzlInsert(zobj->ptr,ele,score);
                    server.dirty++;
1240
                    updated++;
A
antirez 已提交
1241 1242 1243 1244
                }
            } else {
                /* Optimize: check if the element is too large or the list
                 * becomes too long *before* executing zzlInsert. */
1245
                zobj->ptr = zzlInsert(zobj->ptr,ele,score);
A
antirez 已提交
1246 1247 1248 1249
                if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries)
                    zsetConvert(zobj,REDIS_ENCODING_SKIPLIST);
                if (sdslen(ele->ptr) > server.zset_max_ziplist_value)
                    zsetConvert(zobj,REDIS_ENCODING_SKIPLIST);
1250
                server.dirty++;
1251
                added++;
1252
            }
A
antirez 已提交
1253 1254 1255 1256 1257 1258 1259 1260
        } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
            zset *zs = zobj->ptr;
            zskiplistNode *znode;
            dictEntry *de;

            ele = c->argv[3+j*2] = tryObjectEncoding(c->argv[3+j*2]);
            de = dictFind(zs->dict,ele);
            if (de != NULL) {
1261 1262
                curobj = dictGetKey(de);
                curscore = *(double*)dictGetVal(de);
A
antirez 已提交
1263 1264 1265 1266 1267 1268 1269

                if (incr) {
                    score += curscore;
                    if (isnan(score)) {
                        addReplyError(c,nanerr);
                        /* Don't need to check if the sorted set is empty
                         * because we know it has at least one element. */
1270
                        goto cleanup;
A
antirez 已提交
1271
                    }
1272 1273
                }

A
antirez 已提交
1274 1275 1276 1277
                /* Remove and re-insert when score changed. We can safely
                 * delete the key object from the skiplist, since the
                 * dictionary still has a reference to it. */
                if (score != curscore) {
1278
                    redisAssertWithInfo(c,curobj,zslDelete(zs->zsl,curscore,curobj));
A
antirez 已提交
1279 1280
                    znode = zslInsert(zs->zsl,score,curobj);
                    incrRefCount(curobj); /* Re-inserted in skiplist. */
1281
                    dictGetVal(de) = &znode->score; /* Update score ptr. */
A
antirez 已提交
1282
                    server.dirty++;
1283
                    updated++;
A
antirez 已提交
1284 1285 1286 1287
                }
            } else {
                znode = zslInsert(zs->zsl,score,ele);
                incrRefCount(ele); /* Inserted in skiplist. */
A
antirez 已提交
1288
                redisAssertWithInfo(c,NULL,dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
A
antirez 已提交
1289
                incrRefCount(ele); /* Added to dictionary. */
1290
                server.dirty++;
1291
                added++;
1292 1293
            }
        } else {
A
antirez 已提交
1294
            redisPanic("Unknown sorted set encoding");
1295 1296
        }
    }
A
antirez 已提交
1297 1298 1299 1300
    if (incr) /* ZINCRBY */
        addReplyDouble(c,score);
    else /* ZADD */
        addReplyLongLong(c,added);
1301 1302 1303 1304 1305

cleanup:
    zfree(scores);
    if (added || updated) {
        signalModifiedKey(c->db,key);
1306 1307
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
            incr ? "zincr" : "zadd", key, c->db->id);
1308
    }
1309 1310 1311
}

void zaddCommand(redisClient *c) {
1312
    zaddGenericCommand(c,0);
1313 1314 1315
}

void zincrbyCommand(redisClient *c) {
1316
    zaddGenericCommand(c,1);
1317 1318 1319
}

void zremCommand(redisClient *c) {
P
Pieter Noordhuis 已提交
1320 1321
    robj *key = c->argv[1];
    robj *zobj;
1322
    int deleted = 0, keyremoved = 0, j;
P
Pieter Noordhuis 已提交
1323 1324 1325 1326 1327 1328 1329

    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;

    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        unsigned char *eptr;

A
antirez 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338
        for (j = 2; j < c->argc; j++) {
            if ((eptr = zzlFind(zobj->ptr,c->argv[j],NULL)) != NULL) {
                deleted++;
                zobj->ptr = zzlDelete(zobj->ptr,eptr);
                if (zzlLength(zobj->ptr) == 0) {
                    dbDelete(c->db,key);
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1339
        }
1340
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
P
Pieter Noordhuis 已提交
1341 1342 1343 1344
        zset *zs = zobj->ptr;
        dictEntry *de;
        double score;

A
antirez 已提交
1345 1346 1347 1348 1349 1350
        for (j = 2; j < c->argc; j++) {
            de = dictFind(zs->dict,c->argv[j]);
            if (de != NULL) {
                deleted++;

                /* Delete from the skiplist */
1351
                score = *(double*)dictGetVal(de);
1352
                redisAssertWithInfo(c,c->argv[j],zslDelete(zs->zsl,score,c->argv[j]));
A
antirez 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361

                /* Delete from the hash table */
                dictDelete(zs->dict,c->argv[j]);
                if (htNeedsResize(zs->dict)) dictResize(zs->dict);
                if (dictSize(zs->dict) == 0) {
                    dbDelete(c->db,key);
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1362 1363 1364
        }
    } else {
        redisPanic("Unknown sorted set encoding");
1365 1366
    }

A
antirez 已提交
1367
    if (deleted) {
1368 1369 1370
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,"zrem",key,c->db->id);
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
A
antirez 已提交
1371 1372 1373 1374
        signalModifiedKey(c->db,key);
        server.dirty += deleted;
    }
    addReplyLongLong(c,deleted);
1375 1376
}

1377 1378 1379 1380 1381
/* Implements ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX commands. */
#define ZRANGE_RANK 0
#define ZRANGE_SCORE 1
#define ZRANGE_LEX 2
void zremrangeGenericCommand(redisClient *c, int rangetype) {
1382 1383
    robj *key = c->argv[1];
    robj *zobj;
1384
    int keyremoved = 0;
1385
    unsigned long deleted;
1386
    zrangespec range;
A
antirez 已提交
1387
    zlexrangespec lexrange;
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
    long start, end, llen;

    /* Step 1: Parse the range. */
    if (rangetype == ZRANGE_RANK) {
        if ((getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK) ||
            (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK))
            return;
    } else if (rangetype == ZRANGE_SCORE) {
        if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
            addReplyError(c,"min or max is not a float");
            return;
        }
A
antirez 已提交
1400 1401 1402 1403 1404
    } else if (rangetype == ZRANGE_LEX) {
        if (zslParseLexRange(c->argv[2],c->argv[3],&lexrange) != REDIS_OK) {
            addReplyError(c,"min or max not valid string range item");
            return;
        }
1405
    }
1406

1407
    /* Step 2: Lookup & range sanity checks if needed. */
1408
    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1409
        checkType(c,zobj,REDIS_ZSET)) goto cleanup;
1410

1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
    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);
1422
            goto cleanup;
1423 1424 1425 1426 1427
        }
        if (end >= llen) end = llen-1;
    }

    /* Step 3: Perform the range deletion operation. */
1428
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1429 1430 1431 1432 1433
        switch(rangetype) {
        case ZRANGE_RANK:
            zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted);
            break;
        case ZRANGE_SCORE:
1434
            zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,&range,&deleted);
1435
            break;
A
antirez 已提交
1436 1437 1438
        case ZRANGE_LEX:
            zobj->ptr = zzlDeleteRangeByLex(zobj->ptr,&lexrange,&deleted);
            break;
1439
        }
1440 1441 1442 1443
        if (zzlLength(zobj->ptr) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1444
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
1445
        zset *zs = zobj->ptr;
1446 1447 1448 1449 1450
        switch(rangetype) {
        case ZRANGE_RANK:
            deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
            break;
        case ZRANGE_SCORE:
1451
            deleted = zslDeleteRangeByScore(zs->zsl,&range,zs->dict);
1452
            break;
A
antirez 已提交
1453 1454 1455
        case ZRANGE_LEX:
            deleted = zslDeleteRangeByLex(zs->zsl,&lexrange,zs->dict);
            break;
1456
        }
1457
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1458 1459 1460 1461
        if (dictSize(zs->dict) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1462 1463 1464
    } else {
        redisPanic("Unknown sorted set encoding");
    }
1465

1466
    /* Step 4: Notifications and reply. */
1467
    if (deleted) {
1468
        char *event[3] = {"zremrangebyrank","zremrangebyscore","zremrangebylex"};
1469
        signalModifiedKey(c->db,key);
1470
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,event[rangetype],key,c->db->id);
1471 1472
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
1473
    }
1474 1475
    server.dirty += deleted;
    addReplyLongLong(c,deleted);
1476 1477 1478

cleanup:
    if (rangetype == ZRANGE_LEX) zslFreeLexRange(&lexrange);
1479 1480 1481
}

void zremrangebyrankCommand(redisClient *c) {
1482 1483
    zremrangeGenericCommand(c,ZRANGE_RANK);
}
1484

1485 1486
void zremrangebyscoreCommand(redisClient *c) {
    zremrangeGenericCommand(c,ZRANGE_SCORE);
1487 1488
}

A
antirez 已提交
1489 1490 1491 1492
void zremrangebylexCommand(redisClient *c) {
    zremrangeGenericCommand(c,ZRANGE_LEX);
}

1493
typedef struct {
1494 1495 1496
    robj *subject;
    int type; /* Set, sorted set */
    int encoding;
1497
    double weight;
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524

    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;
1525 1526
} zsetopsrc;

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576

/* 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. */
#define OPVAL_DIRTY_ROBJ 1
#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. */
    robj *ele;
    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;

    if (op->type == REDIS_SET) {
        iterset *it = &op->iter.set;
        if (op->encoding == REDIS_ENCODING_INTSET) {
            it->is.is = op->subject->ptr;
            it->is.ii = 0;
        } else if (op->encoding == REDIS_ENCODING_HT) {
            it->ht.dict = op->subject->ptr;
            it->ht.di = dictGetIterator(op->subject->ptr);
            it->ht.de = dictNext(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        iterzset *it = &op->iter.zset;
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
            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);
                redisAssert(it->zl.sptr != NULL);
            }
1577
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
            it->sl.zs = op->subject->ptr;
            it->sl.node = it->sl.zs->zsl->header->level[0].forward;
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

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

    if (op->type == REDIS_SET) {
        iterset *it = &op->iter.set;
        if (op->encoding == REDIS_ENCODING_INTSET) {
            REDIS_NOTUSED(it); /* skip */
        } else if (op->encoding == REDIS_ENCODING_HT) {
            dictReleaseIterator(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        iterzset *it = &op->iter.zset;
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
            REDIS_NOTUSED(it); /* skip */
1605
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
            REDIS_NOTUSED(it); /* skip */
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

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

    if (op->type == REDIS_SET) {
        if (op->encoding == REDIS_ENCODING_INTSET) {
1621
            return intsetLen(op->subject->ptr);
1622
        } else if (op->encoding == REDIS_ENCODING_HT) {
1623 1624
            dict *ht = op->subject->ptr;
            return dictSize(ht);
1625 1626 1627 1628 1629
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1630
            return zzlLength(op->subject->ptr);
1631
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1632 1633
            zset *zs = op->subject->ptr;
            return zs->zsl->length;
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

/* 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;

    if (val->flags & OPVAL_DIRTY_ROBJ)
        decrRefCount(val->ele);

A
antirez 已提交
1652
    memset(val,0,sizeof(zsetopval));
1653 1654 1655 1656

    if (op->type == REDIS_SET) {
        iterset *it = &op->iter.set;
        if (op->encoding == REDIS_ENCODING_INTSET) {
1657
            int64_t ell;
A
antirez 已提交
1658 1659

            if (!intsetGet(it->is.is,it->is.ii,&ell))
1660
                return 0;
1661
            val->ell = ell;
1662 1663 1664 1665 1666 1667 1668
            val->score = 1.0;

            /* Move to next element. */
            it->is.ii++;
        } else if (op->encoding == REDIS_ENCODING_HT) {
            if (it->ht.de == NULL)
                return 0;
1669
            val->ele = dictGetKey(it->ht.de);
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
            val->score = 1.0;

            /* Move to next element. */
            it->ht.de = dictNext(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        iterzset *it = &op->iter.zset;
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
            /* No need to check both, but better be explicit. */
            if (it->zl.eptr == NULL || it->zl.sptr == NULL)
                return 0;
            redisAssert(ziplistGet(it->zl.eptr,&val->estr,&val->elen,&val->ell));
            val->score = zzlGetScore(it->zl.sptr);

            /* Move to next element. */
            zzlNext(it->zl.zl,&it->zl.eptr,&it->zl.sptr);
1688
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
            if (it->sl.node == NULL)
                return 0;
            val->ele = it->sl.node->obj;
            val->score = it->sl.node->score;

            /* Move to next element. */
            it->sl.node = it->sl.node->level[0].forward;
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
    return 1;
}

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

        if (val->ele != NULL) {
            if (val->ele->encoding == REDIS_ENCODING_INT) {
                val->ell = (long)val->ele->ptr;
                val->flags |= OPVAL_VALID_LL;
1713
            } else if (sdsEncodedObject(val->ele)) {
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
                if (string2ll(val->ele->ptr,sdslen(val->ele->ptr),&val->ell))
                    val->flags |= OPVAL_VALID_LL;
            } else {
                redisPanic("Unsupported element encoding");
            }
        } 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;
}

robj *zuiObjectFromValue(zsetopval *val) {
    if (val->ele == NULL) {
        if (val->estr != NULL) {
            val->ele = createStringObject((char*)val->estr,val->elen);
        } else {
            val->ele = createStringObjectFromLongLong(val->ell);
        }
        val->flags |= OPVAL_DIRTY_ROBJ;
    }
    return val->ele;
}

int zuiBufferFromValue(zsetopval *val) {
    if (val->estr == NULL) {
        if (val->ele != NULL) {
            if (val->ele->encoding == REDIS_ENCODING_INT) {
                val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),(long)val->ele->ptr);
                val->estr = val->_buf;
1748
            } else if (sdsEncodedObject(val->ele)) {
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
                val->elen = sdslen(val->ele->ptr);
                val->estr = val->ele->ptr;
            } else {
                redisPanic("Unsupported element encoding");
            }
        } 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;

    if (op->type == REDIS_SET) {
        if (op->encoding == REDIS_ENCODING_INTSET) {
1770 1771 1772
            if (zuiLongLongFromValue(val) &&
                intsetFind(op->subject->ptr,val->ell))
            {
1773 1774 1775 1776 1777 1778
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else if (op->encoding == REDIS_ENCODING_HT) {
1779
            dict *ht = op->subject->ptr;
1780
            zuiObjectFromValue(val);
1781
            if (dictFind(ht,val->ele) != NULL) {
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        zuiObjectFromValue(val);

        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1794
            if (zzlFind(op->subject->ptr,val->ele,score) != NULL) {
1795 1796 1797 1798 1799
                /* Score is already set by zzlFind. */
                return 1;
            } else {
                return 0;
            }
1800
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1801
            zset *zs = op->subject->ptr;
1802
            dictEntry *de;
1803
            if ((de = dictFind(zs->dict,val->ele)) != NULL) {
1804
                *score = *(double*)dictGetVal(de);
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
                return 1;
            } else {
                return 0;
            }
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

int zuiCompareByCardinality(const void *s1, const void *s2) {
    return zuiLength((zsetopsrc*)s1) - zuiLength((zsetopsrc*)s2);
1819 1820 1821 1822 1823
}

#define REDIS_AGGR_SUM 1
#define REDIS_AGGR_MIN 2
#define REDIS_AGGR_MAX 3
1824
#define zunionInterDictValue(_e) (dictGetVal(_e) == NULL ? 1.0 : *(double*)dictGetVal(_e))
1825 1826 1827 1828

inline static void zunionInterAggregate(double *target, double val, int aggregate) {
    if (aggregate == REDIS_AGGR_SUM) {
        *target = *target + val;
1829 1830 1831 1832
        /* 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;
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
    } 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 */
        redisPanic("Unknown ZUNION/INTER aggregate type");
    }
}

void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
1844 1845
    int i, j;
    long setnum;
1846 1847
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
1848 1849
    zsetopval zval;
    robj *tmp;
1850
    unsigned int maxelelen = 0;
1851 1852
    robj *dstobj;
    zset *dstzset;
1853
    zskiplistNode *znode;
1854
    int touched = 0;
1855 1856

    /* expect setnum input keys to be given */
1857 1858 1859
    if ((getLongFromObjectOrReply(c, c->argv[2], &setnum, NULL) != REDIS_OK))
        return;

1860
    if (setnum < 1) {
1861 1862
        addReplyError(c,
            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1863 1864 1865 1866
        return;
    }

    /* test if the expected number of keys would overflow */
1867
    if (setnum > c->argc-3) {
1868 1869 1870 1871 1872
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
1873
    src = zcalloc(sizeof(zsetopsrc) * setnum);
1874 1875
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
1876 1877
        if (obj != NULL) {
            if (obj->type != REDIS_ZSET && obj->type != REDIS_SET) {
1878 1879 1880 1881
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
1882 1883 1884 1885 1886 1887

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

1890
        /* Default all weights to 1. */
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
        src[i].weight = 1.0;
    }

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

        while (remaining) {
            if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
                j++; remaining--;
                for (i = 0; i < setnum; i++, j++, remaining--) {
1902
                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
1903
                            "weight value is not a float") != REDIS_OK)
1904 1905
                    {
                        zfree(src);
1906
                        return;
1907
                    }
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
                }
            } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
                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 */
1933
    qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality);
1934 1935 1936

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;
1937
    memset(&zval, 0, sizeof(zval));
1938 1939

    if (op == REDIS_OP_INTER) {
1940 1941 1942 1943
        /* 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. */
1944
            zuiInitIterator(&src[0]);
1945
            while (zuiNext(&src[0],&zval)) {
1946
                double score, value;
1947

1948
                score = src[0].weight * zval.score;
1949 1950
                if (isnan(score)) score = 0;

1951
                for (j = 1; j < setnum; j++) {
A
antirez 已提交
1952
                    /* It is not safe to access the zset we are
1953
                     * iterating, so explicitly check for equal object. */
1954 1955 1956 1957
                    if (src[j].subject == src[0].subject) {
                        value = zval.score*src[j].weight;
                        zunionInterAggregate(&score,value,aggregate);
                    } else if (zuiFind(&src[j],&zval,&value)) {
1958
                        value *= src[j].weight;
1959
                        zunionInterAggregate(&score,value,aggregate);
1960 1961 1962 1963 1964
                    } else {
                        break;
                    }
                }

1965
                /* Only continue when present in every input. */
1966
                if (j == setnum) {
1967 1968 1969 1970 1971
                    tmp = zuiObjectFromValue(&zval);
                    znode = zslInsert(dstzset->zsl,score,tmp);
                    incrRefCount(tmp); /* added to skiplist */
                    dictAdd(dstzset->dict,tmp,&znode->score);
                    incrRefCount(tmp); /* added to dictionary */
1972

1973
                    if (sdsEncodedObject(tmp)) {
1974 1975
                        if (sdslen(tmp->ptr) > maxelelen)
                            maxelelen = sdslen(tmp->ptr);
1976
                    }
1977 1978
                }
            }
1979
            zuiClearIterator(&src[0]);
1980 1981 1982
        }
    } else if (op == REDIS_OP_UNION) {
        for (i = 0; i < setnum; i++) {
1983
            if (zuiLength(&src[i]) == 0)
1984
                continue;
1985

1986
            zuiInitIterator(&src[i]);
1987
            while (zuiNext(&src[i],&zval)) {
1988 1989
                double score, value;

1990
                /* Skip an element that when already processed */
1991
                if (dictFind(dstzset->dict,zuiObjectFromValue(&zval)) != NULL)
1992
                    continue;
1993

1994 1995
                /* Initialize score */
                score = src[i].weight * zval.score;
1996
                if (isnan(score)) score = 0;
1997

1998 1999 2000 2001
                /* We need to check only next sets to see if this element
                 * exists, since we process every element just one time so
                 * it can't exist in a previous set (otherwise it would be
                 * already processed). */
2002
                for (j = (i+1); j < setnum; j++) {
A
antirez 已提交
2003
                    /* It is not safe to access the zset we are
2004 2005 2006 2007 2008
                     * iterating, so explicitly check for equal object. */
                    if(src[j].subject == src[i].subject) {
                        value = zval.score*src[j].weight;
                        zunionInterAggregate(&score,value,aggregate);
                    } else if (zuiFind(&src[j],&zval,&value)) {
2009
                        value *= src[j].weight;
2010
                        zunionInterAggregate(&score,value,aggregate);
2011 2012 2013
                    }
                }

2014 2015 2016 2017 2018
                tmp = zuiObjectFromValue(&zval);
                znode = zslInsert(dstzset->zsl,score,tmp);
                incrRefCount(zval.ele); /* added to skiplist */
                dictAdd(dstzset->dict,tmp,&znode->score);
                incrRefCount(zval.ele); /* added to dictionary */
2019

2020
                if (sdsEncodedObject(tmp)) {
2021 2022
                    if (sdslen(tmp->ptr) > maxelelen)
                        maxelelen = sdslen(tmp->ptr);
2023
                }
2024
            }
2025
            zuiClearIterator(&src[i]);
2026 2027
        }
    } else {
2028
        redisPanic("Unknown operator");
2029 2030
    }

2031
    if (dbDelete(c->db,dstkey)) {
2032
        signalModifiedKey(c->db,dstkey);
2033 2034 2035
        touched = 1;
        server.dirty++;
    }
2036
    if (dstzset->zsl->length) {
2037 2038 2039
        /* Convert to ziplist when in limits. */
        if (dstzset->zsl->length <= server.zset_max_ziplist_entries &&
            maxelelen <= server.zset_max_ziplist_value)
2040
                zsetConvert(dstobj,REDIS_ENCODING_ZIPLIST);
2041

2042
        dbAdd(c->db,dstkey,dstobj);
2043
        addReplyLongLong(c,zsetLength(dstobj));
2044
        if (!touched) signalModifiedKey(c->db,dstkey);
2045
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
2046 2047
            (op == REDIS_OP_UNION) ? "zunionstore" : "zinterstore",
            dstkey,c->db->id);
A
antirez 已提交
2048
        server.dirty++;
2049 2050
    } else {
        decrRefCount(dstobj);
2051
        addReply(c,shared.czero);
2052 2053
        if (touched)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",dstkey,c->db->id);
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
    }
    zfree(src);
}

void zunionstoreCommand(redisClient *c) {
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
}

void zinterstoreCommand(redisClient *c) {
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
}

void zrangeGenericCommand(redisClient *c, int reverse) {
2067 2068 2069
    robj *key = c->argv[1];
    robj *zobj;
    int withscores = 0;
2070 2071 2072
    long start;
    long end;
    int llen;
2073
    int rangelen;
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084

    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;

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

2085 2086
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
         || checkType(c,zobj,REDIS_ZSET)) return;
2087

2088
    /* Sanitize indexes. */
2089
    llen = zsetLength(zobj);
2090 2091 2092 2093
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

2094 2095
    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
2096 2097 2098 2099 2100 2101 2102 2103
    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 */
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);

    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        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);

2118
        redisAssertWithInfo(c,zobj,eptr != NULL);
2119 2120
        sptr = ziplistNext(zl,eptr);

2121
        while (rangelen--) {
2122 2123
            redisAssertWithInfo(c,zobj,eptr != NULL && sptr != NULL);
            redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2124 2125 2126 2127 2128
            if (vstr == NULL)
                addReplyBulkLongLong(c,vlong);
            else
                addReplyBulkCBuffer(c,vstr,vlen);

2129
            if (withscores)
2130 2131
                addReplyDouble(c,zzlGetScore(sptr));

2132 2133 2134 2135
            if (reverse)
                zzlPrev(zl,&eptr,&sptr);
            else
                zzlNext(zl,&eptr,&sptr);
2136 2137
        }

2138
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
        robj *ele;

        /* 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--) {
2156
            redisAssertWithInfo(c,zobj,ln != NULL);
2157 2158 2159 2160 2161 2162 2163 2164
            ele = ln->obj;
            addReplyBulk(c,ele);
            if (withscores)
                addReplyDouble(c,ln->score);
            ln = reverse ? ln->backward : ln->level[0].forward;
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
    }
}

void zrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,0);
}

void zrevrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,1);
}

2176 2177
/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */
void genericZrangebyscoreCommand(redisClient *c, int reverse) {
2178
    zrangespec range;
2179
    robj *key = c->argv[1];
2180
    robj *zobj;
2181
    long offset = 0, limit = -1;
2182
    int withscores = 0;
2183 2184
    unsigned long rangelen = 0;
    void *replylen = NULL;
2185
    int minidx, maxidx;
2186

2187
    /* Parse the range arguments. */
2188 2189 2190 2191 2192 2193 2194 2195 2196
    if (reverse) {
        /* Range is given as [max,min] */
        maxidx = 2; minidx = 3;
    } else {
        /* Range is given as [min,max] */
        minidx = 2; maxidx = 3;
    }

    if (zslParseRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) {
2197
        addReplyError(c,"min or max is not a float");
2198 2199
        return;
    }
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211

    /* 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")) {
2212 2213
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return;
2214 2215 2216 2217 2218 2219
                pos += 3; remaining -= 3;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }
2220
    }
2221 2222

    /* Ok, lookup the key and get the range */
2223
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2224
        checkType(c,zobj,REDIS_ZSET)) return;
2225

2226 2227 2228 2229 2230 2231 2232
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;
        double score;
2233

2234
        /* If reversed, get the last node in range as starting point. */
2235
        if (reverse) {
2236
            eptr = zzlLastInRange(zl,&range);
2237
        } else {
2238
            eptr = zzlFirstInRange(zl,&range);
2239
        }
2240

2241 2242
        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
2243
            addReply(c, shared.emptymultibulk);
2244 2245
            return;
        }
2246

2247
        /* Get score pointer for the first element. */
2248
        redisAssertWithInfo(c,zobj,eptr != NULL);
2249
        sptr = ziplistNext(zl,eptr);
2250

2251 2252 2253
        /* 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 */
2254
        replylen = addDeferredMultiBulkLength(c);
2255 2256 2257

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2258 2259
        while (eptr && offset--) {
            if (reverse) {
2260
                zzlPrev(zl,&eptr,&sptr);
2261
            } else {
2262
                zzlNext(zl,&eptr,&sptr);
2263 2264
            }
        }
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275

        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;
            }

2276
            /* We know the element exists, so ziplistGet should always succeed */
2277
            redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2278

2279
            rangelen++;
2280 2281 2282 2283 2284 2285 2286 2287
            if (vstr == NULL) {
                addReplyBulkLongLong(c,vlong);
            } else {
                addReplyBulkCBuffer(c,vstr,vlen);
            }

            if (withscores) {
                addReplyDouble(c,score);
2288 2289 2290
            }

            /* Move to next node */
2291
            if (reverse) {
2292
                zzlPrev(zl,&eptr,&sptr);
2293
            } else {
2294
                zzlNext(zl,&eptr,&sptr);
2295
            }
2296
        }
2297
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2298 2299 2300
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
2301

2302
        /* If reversed, get the last node in range as starting point. */
2303
        if (reverse) {
2304
            ln = zslLastInRange(zsl,&range);
2305
        } else {
2306
            ln = zslFirstInRange(zsl,&range);
2307
        }
2308 2309 2310

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
2311
            addReply(c, shared.emptymultibulk);
2312
            return;
2313 2314
        }

2315 2316 2317
        /* 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 */
2318
        replylen = addDeferredMultiBulkLength(c);
2319 2320 2321

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2322 2323 2324 2325 2326 2327 2328
        while (ln && offset--) {
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338

        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++;
2339 2340 2341 2342
            addReplyBulk(c,ln->obj);

            if (withscores) {
                addReplyDouble(c,ln->score);
2343 2344 2345
            }

            /* Move to next node */
2346 2347 2348 2349 2350
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
2351 2352 2353
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2354 2355
    }

2356 2357
    if (withscores) {
        rangelen *= 2;
2358
    }
2359 2360

    setDeferredMultiBulkLength(c, replylen, rangelen);
2361 2362 2363
}

void zrangebyscoreCommand(redisClient *c) {
2364
    genericZrangebyscoreCommand(c,0);
2365 2366 2367
}

void zrevrangebyscoreCommand(redisClient *c) {
2368
    genericZrangebyscoreCommand(c,1);
2369 2370 2371
}

void zcountCommand(redisClient *c) {
2372 2373 2374 2375 2376 2377 2378
    robj *key = c->argv[1];
    robj *zobj;
    zrangespec range;
    int count = 0;

    /* Parse the range arguments */
    if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
2379
        addReplyError(c,"min or max is not a float");
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
        return;
    }

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

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

        /* Use the first element in range as the starting point */
2393
        eptr = zzlFirstInRange(zl,&range);
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403

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

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
        score = zzlGetScore(sptr);
2404
        redisAssertWithInfo(c,zobj,zslValueLteMax(score,&range));
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424

        /* 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);
            }
        }
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2425
        zn = zslFirstInRange(zsl, &range);
2426 2427 2428 2429 2430 2431 2432

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

            /* Find last element in range */
2433
            zn = zslLastInRange(zsl, &range);
2434 2435 2436 2437 2438 2439 2440 2441 2442

            /* Use rank of last element, if any, to determine the actual count */
            if (zn != NULL) {
                rank = zslGetRank(zsl, zn->score, zn->obj);
                count -= (zsl->length - rank);
            }
        }
    } else {
        redisPanic("Unknown sorted set encoding");
A
antirez 已提交
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    }

    addReplyLongLong(c, count);
}

void zlexcountCommand(redisClient *c) {
    robj *key = c->argv[1];
    robj *zobj;
    zlexrangespec range;
    int count = 0;

    /* Parse the range arguments */
    if (zslParseLexRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
        addReplyError(c,"min or max not valid string range item");
        return;
    }

    /* Lookup the sorted set */
    if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL ||
2462 2463 2464 2465 2466
        checkType(c, zobj, REDIS_ZSET))
    {
        zslFreeLexRange(&range);
        return;
    }
A
antirez 已提交
2467 2468 2469 2470 2471 2472

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

        /* Use the first element in range as the starting point */
2473
        eptr = zzlFirstInLexRange(zl,&range);
A
antirez 已提交
2474 2475 2476

        /* No "first" element */
        if (eptr == NULL) {
2477
            zslFreeLexRange(&range);
A
antirez 已提交
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
            addReply(c, shared.czero);
            return;
        }

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
        redisAssertWithInfo(c,zobj,zzlLexValueLteMax(eptr,&range));

        /* 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);
            }
        }
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2503
        zn = zslFirstInLexRange(zsl, &range);
A
antirez 已提交
2504 2505 2506 2507 2508 2509 2510

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

            /* Find last element in range */
2511
            zn = zslLastInLexRange(zsl, &range);
A
antirez 已提交
2512 2513 2514 2515 2516 2517 2518 2519 2520

            /* Use rank of last element, if any, to determine the actual count */
            if (zn != NULL) {
                rank = zslGetRank(zsl, zn->score, zn->obj);
                count -= (zsl->length - rank);
            }
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2521 2522
    }

2523
    zslFreeLexRange(&range);
2524
    addReplyLongLong(c, count);
2525 2526
}

2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
/* This command implements ZRANGEBYLEX, ZREVRANGEBYLEX. */
void genericZrangebylexCommand(redisClient *c, int reverse) {
    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;
    }

    if (zslParseLexRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) {
        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")) {
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return;
                pos += 3; remaining -= 3;
            } else {
2563
                zslFreeLexRange(&range);
2564 2565 2566 2567 2568 2569 2570 2571
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* Ok, lookup the key and get the range */
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2572 2573 2574 2575 2576
        checkType(c,zobj,REDIS_ZSET))
    {
        zslFreeLexRange(&range);
        return;
    }
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586

    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        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) {
2587
            eptr = zzlLastInLexRange(zl,&range);
2588
        } else {
2589
            eptr = zzlFirstInLexRange(zl,&range);
2590 2591 2592 2593 2594
        }

        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
            addReply(c, shared.emptymultibulk);
2595
            zslFreeLexRange(&range);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
            return;
        }

        /* Get score pointer for the first element. */
        redisAssertWithInfo(c,zobj,eptr != NULL);
        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. */
            redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));

            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);
            }
        }
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2651
            ln = zslLastInLexRange(zsl,&range);
2652
        } else {
2653
            ln = zslFirstInLexRange(zsl,&range);
2654 2655 2656 2657 2658
        }

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
            addReply(c, shared.emptymultibulk);
2659
            zslFreeLexRange(&range);
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
            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) {
                if (!zslLexValueGteMin(ln->obj,&range)) break;
            } else {
                if (!zslLexValueLteMax(ln->obj,&range)) break;
            }

            rangelen++;
            addReplyBulk(c,ln->obj);

            /* Move to next node */
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
    } else {
        redisPanic("Unknown sorted set encoding");
    }

2700
    zslFreeLexRange(&range);
2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
    setDeferredMultiBulkLength(c, replylen, rangelen);
}

void zrangebylexCommand(redisClient *c) {
    genericZrangebylexCommand(c,0);
}

void zrevrangebylexCommand(redisClient *c) {
    genericZrangebylexCommand(c,1);
}

2712
void zcardCommand(redisClient *c) {
2713 2714
    robj *key = c->argv[1];
    robj *zobj;
2715

2716 2717
    if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2718

2719
    addReplyLongLong(c,zsetLength(zobj));
2720 2721 2722
}

void zscoreCommand(redisClient *c) {
2723 2724 2725
    robj *key = c->argv[1];
    robj *zobj;
    double score;
2726

2727 2728
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2729

2730
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
2731
        if (zzlFind(zobj->ptr,c->argv[2],&score) != NULL)
2732 2733 2734
            addReplyDouble(c,score);
        else
            addReply(c,shared.nullbulk);
2735
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2736 2737
        zset *zs = zobj->ptr;
        dictEntry *de;
2738

2739 2740 2741
        c->argv[2] = tryObjectEncoding(c->argv[2]);
        de = dictFind(zs->dict,c->argv[2]);
        if (de != NULL) {
2742
            score = *(double*)dictGetVal(de);
2743 2744 2745 2746 2747 2748
            addReplyDouble(c,score);
        } else {
            addReply(c,shared.nullbulk);
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2749 2750 2751 2752
    }
}

void zrankGenericCommand(redisClient *c, int reverse) {
2753 2754 2755 2756
    robj *key = c->argv[1];
    robj *ele = c->argv[2];
    robj *zobj;
    unsigned long llen;
2757 2758
    unsigned long rank;

2759 2760
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2761
    llen = zsetLength(zobj);
2762

2763 2764
    redisAssertWithInfo(c,ele,sdsEncodedObject(ele));

2765 2766 2767
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
2768

2769
        eptr = ziplistIndex(zl,0);
2770
        redisAssertWithInfo(c,zobj,eptr != NULL);
2771
        sptr = ziplistNext(zl,eptr);
2772
        redisAssertWithInfo(c,zobj,sptr != NULL);
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786

        rank = 1;
        while(eptr != NULL) {
            if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr)))
                break;
            rank++;
            zzlNext(zl,&eptr,&sptr);
        }

        if (eptr != NULL) {
            if (reverse)
                addReplyLongLong(c,llen-rank);
            else
                addReplyLongLong(c,rank-1);
2787
        } else {
2788 2789
            addReply(c,shared.nullbulk);
        }
2790
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2791 2792 2793 2794 2795 2796 2797 2798
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        dictEntry *de;
        double score;

        ele = c->argv[2] = tryObjectEncoding(c->argv[2]);
        de = dictFind(zs->dict,ele);
        if (de != NULL) {
2799
            score = *(double*)dictGetVal(de);
2800
            rank = zslGetRank(zsl,score,ele);
2801
            redisAssertWithInfo(c,ele,rank); /* Existing elements always have a rank. */
2802 2803 2804 2805 2806 2807
            if (reverse)
                addReplyLongLong(c,llen-rank);
            else
                addReplyLongLong(c,rank-1);
        } else {
            addReply(c,shared.nullbulk);
2808 2809
        }
    } else {
2810
        redisPanic("Unknown sorted set encoding");
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
    }
}

void zrankCommand(redisClient *c) {
    zrankGenericCommand(c, 0);
}

void zrevrankCommand(redisClient *c) {
    zrankGenericCommand(c, 1);
}
A
antirez 已提交
2821 2822 2823

void zscanCommand(redisClient *c) {
    robj *o;
2824
    unsigned long cursor;
A
antirez 已提交
2825

2826
    if (parseScanCursorOrReply(c,c->argv[2],&cursor) == REDIS_ERR) return;
2827
    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL ||
A
antirez 已提交
2828
        checkType(c,o,REDIS_ZSET)) return;
2829
    scanGenericCommand(c,o,cursor);
A
antirez 已提交
2830
}