t_zset.c 93.9 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
#include "server.h"
53 54
#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
    if (x && score == x->score && equalStringObjects(x->obj,obj)) {
        zslDeleteNode(zsl, x, update);
        zslFreeNode(x);
        return 1;
    }
    return 0; /* not found */
}

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

M
Matt Stancliff 已提交
216
int zslValueLteMax(double value, zrangespec *spec) {
217 218 219 220 221 222 223
    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;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A
antirez 已提交
323 324 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
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;
}

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

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

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
393 394 395 396 397 398
        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;
399 400 401 402 403 404 405 406 407 408 409
        }

        /* 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. */
410
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
411 412 413 414 415 416
    zskiplistNode *x;
    unsigned long traversed = 0;
    int i;

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

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

    return REDIS_OK;
}

466 467 468 469 470 471 472 473 474 475 476 477 478
/* ------------------------ 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.
  *
479
  * If the string is not a valid range REDIS_ERR is returned, and the value
480 481 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
  * 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;
    }
}

510 511 512 513 514
/* 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. */
515
static int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec) {
516 517
    /* The range can't be valid if objects are integer encoded.
     * Every item must start with ( or [. */
518 519
    if (min->encoding == OBJ_ENCODING_INT ||
        max->encoding == OBJ_ENCODING_INT) return REDIS_ERR;
520 521 522 523 524 525 526 527 528 529 530 531

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

532 533 534 535 536 537 538
/* 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);
}

539 540 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
/* 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. */
582
zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range) {
583 584 585 586
    zskiplistNode *x;
    int i;

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

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* Go forward while *OUT* of range. */
        while (x->level[i].forward &&
593
            !zslLexValueGteMin(x->level[i].forward->obj,range))
594 595 596 597 598 599 600 601
                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. */
602
    if (!zslLexValueLteMax(x->obj,range)) return NULL;
603 604 605 606 607
    return x;
}

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

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

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

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

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

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
/*-----------------------------------------------------------------------------
 * 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;
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
/* 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);
    }
}

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

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

699 700 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
/* 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;
}

737 738 739 740 741 742 743 744 745 746 747 748
/* 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. */
749
    if (p == NULL) return 0; /* Empty sorted set */
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
    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. */
765
unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range) {
766 767 768 769
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;
    double score;

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

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

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

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

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

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

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

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

824 825 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
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. */
864
unsigned char *zzlFirstInLexRange(unsigned char *zl, zlexrangespec *range) {
865 866 867
    unsigned char *eptr = ziplistIndex(zl,0), *sptr;

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

    while (eptr != NULL) {
871
        if (zzlLexValueGteMin(eptr,range)) {
872
            /* Check if score <= max. */
873
            if (zzlLexValueLteMax(eptr,range))
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
                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. */
889
unsigned char *zzlLastInLexRange(unsigned char *zl, zlexrangespec *range) {
890 891 892
    unsigned char *eptr = ziplistIndex(zl,-2), *sptr;

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

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

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

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

        if (ziplistCompare(eptr,ele->ptr,sdslen(ele->ptr))) {
            /* Matching element, pull out score. */
P
Pieter Noordhuis 已提交
925
            if (score != NULL) *score = zzlGetScore(sptr);
926 927 928 929 930 931 932 933 934 935 936 937 938 939
            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. */
940
unsigned char *zzlDelete(unsigned char *zl, unsigned char *eptr) {
941 942 943 944 945
    unsigned char *p = eptr;

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

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

955
    redisAssertWithInfo(NULL,ele,sdsEncodedObject(ele));
956 957 958 959 960 961 962 963 964 965 966
    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. */
967
        redisAssertWithInfo(NULL,ele,(sptr = ziplistNext(zl,eptr)) != NULL);
968 969 970
        zl = ziplistInsert(zl,sptr,(unsigned char*)scorebuf,scorelen);
    }

971
    return zl;
972 973 974 975
}

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

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

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

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

    decrRefCount(ele);
1009
    return zl;
1010
}
1011

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

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

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

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

1037 1038
    if (deleted != NULL) *deleted = num;
    return zl;
1039 1040
}

A
antirez 已提交
1041 1042 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
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;
}

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

1077 1078 1079 1080
/*-----------------------------------------------------------------------------
 * Common sorted set API
 *----------------------------------------------------------------------------*/

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

1093
void zsetConvert(robj *zobj, int encoding) {
1094 1095 1096 1097 1098 1099
    zset *zs;
    zskiplistNode *node, *next;
    robj *ele;
    double score;

    if (zobj->encoding == encoding) return;
1100
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1101 1102 1103 1104 1105 1106
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;

1107
        if (encoding != OBJ_ENCODING_SKIPLIST)
1108 1109 1110 1111 1112 1113 1114
            redisPanic("Unknown target encoding");

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

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

        while (eptr != NULL) {
            score = zzlGetScore(sptr);
1121
            redisAssertWithInfo(NULL,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
1122 1123 1124 1125 1126 1127 1128
            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);
1129
            redisAssertWithInfo(NULL,zobj,dictAdd(zs->dict,ele,&node->score) == DICT_OK);
1130 1131 1132 1133 1134 1135
            incrRefCount(ele); /* Added to dictionary. */
            zzlNext(zl,&eptr,&sptr);
        }

        zfree(zobj->ptr);
        zobj->ptr = zs;
1136 1137
        zobj->encoding = OBJ_ENCODING_SKIPLIST;
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
1138 1139
        unsigned char *zl = ziplistNew();

1140
        if (encoding != OBJ_ENCODING_ZIPLIST)
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
            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);
1153
            zl = zzlInsertAt(zl,NULL,ele,node->score);
1154 1155 1156 1157 1158 1159 1160 1161
            decrRefCount(ele);

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

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

A
antirez 已提交
1169 1170 1171 1172 1173 1174 1175
/* Return (by reference) the score of the specified member of the sorted set
 * storing it into *score. If the element does not exist REDIS_ERR is returned
 * otherwise REDIS_OK is returned and *score is correctly populated.
 * If 'zobj' or 'member' is NULL, REDIS_ERR is returned. */
int zsetScore(robj *zobj, robj *member, double *score) {
    if (!zobj || !member) return REDIS_ERR;

1176
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
A
antirez 已提交
1177
        if (zzlFind(zobj->ptr, member, score) == NULL) return REDIS_ERR;
1178
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        zset *zs = zobj->ptr;
        dictEntry *de = dictFind(zs->dict, member);
        if (de == NULL) return REDIS_ERR;
        *score = *(double*)dictGetVal(de);
    } else {
        redisPanic("Unknown sorted set encoding");
    }
    return REDIS_OK;
}

1189
/*-----------------------------------------------------------------------------
1190
 * Sorted set commands
1191 1192
 *----------------------------------------------------------------------------*/

1193
/* This generic command implements both ZADD and ZINCRBY. */
1194 1195 1196 1197
#define ZADD_NONE 0
#define ZADD_INCR (1<<0)    /* Increment the score instead of setting it. */
#define ZADD_NX (1<<1)      /* Don't touch elements not already existing. */
#define ZADD_XX (1<<2)      /* Only touch elements already exisitng. */
A
antirez 已提交
1198
#define ZADD_CH (1<<3)      /* Return num of elements added or updated. */
1199
void zaddGenericCommand(client *c, int flags) {
1200
    static char *nanerr = "resulting score is not a number (NaN)";
1201 1202
    robj *key = c->argv[1];
    robj *ele;
1203 1204
    robj *zobj;
    robj *curobj;
1205
    double score = 0, *scores = NULL, curscore = 0.0;
1206
    int j, elements;
A
antirez 已提交
1207 1208 1209 1210 1211 1212 1213 1214
    int scoreidx = 0;
    /* The following vars are used in order to track what the command actually
     * did during the execution, to reply to the client and to trigger the
     * notification of keyspace change. */
    int added = 0;      /* Number of new elements added. */
    int updated = 0;    /* Number of elements with updated score. */
    int processed = 0;  /* Number of elements processed, may remain zero with
                           options like XX. */
1215 1216 1217 1218 1219 1220 1221 1222

    /* Parse options. At the end 'scoreidx' is set to the argument position
     * of the score of the first score-element pair. */
    scoreidx = 2;
    while(scoreidx < c->argc) {
        char *opt = c->argv[scoreidx]->ptr;
        if (!strcasecmp(opt,"nx")) flags |= ZADD_NX;
        else if (!strcasecmp(opt,"xx")) flags |= ZADD_XX;
A
antirez 已提交
1223
        else if (!strcasecmp(opt,"ch")) flags |= ZADD_CH;
1224 1225 1226 1227 1228 1229 1230 1231 1232
        else if (!strcasecmp(opt,"incr")) flags |= ZADD_INCR;
        else break;
        scoreidx++;
    }

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

1235 1236 1237 1238
    /* After the options, we expect to have an even number of args, since
     * we expect any number of score-element pairs. */
    elements = c->argc-scoreidx;
    if (elements % 2) {
A
antirez 已提交
1239
        addReply(c,shared.syntaxerr);
1240
        return;
A
antirez 已提交
1241
    }
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    elements /= 2; /* Now this holds the number of score-element pairs. */

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

    if (incr && elements > 1) {
        addReplyError(c,
            "INCR option supports a single increment-element pair");
        return;
    }
A
antirez 已提交
1256 1257 1258 1259 1260 1261

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

A
antirez 已提交
1266
    /* Lookup the key and create the sorted set if does not exist. */
1267 1268
    zobj = lookupKeyWrite(c->db,key);
    if (zobj == NULL) {
A
antirez 已提交
1269
        if (xx) goto reply_to_client; /* No key + XX option: nothing to do. */
1270
        if (server.zset_max_ziplist_entries == 0 ||
L
linfangrong 已提交
1271
            server.zset_max_ziplist_value < sdslen(c->argv[scoreidx+1]->ptr))
1272 1273 1274 1275 1276
        {
            zobj = createZsetObject();
        } else {
            zobj = createZsetZiplistObject();
        }
1277
        dbAdd(c->db,key,zobj);
1278
    } else {
1279
        if (zobj->type != OBJ_ZSET) {
1280
            addReply(c,shared.wrongtypeerr);
1281
            goto cleanup;
1282 1283 1284
        }
    }

A
antirez 已提交
1285 1286 1287
    for (j = 0; j < elements; j++) {
        score = scores[j];

1288
        if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
A
antirez 已提交
1289 1290 1291
            unsigned char *eptr;

            /* Prefer non-encoded element when dealing with ziplists. */
1292
            ele = c->argv[scoreidx+1+j*2];
A
antirez 已提交
1293
            if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
A
antirez 已提交
1294
                if (nx) continue;
A
antirez 已提交
1295 1296 1297 1298
                if (incr) {
                    score += curscore;
                    if (isnan(score)) {
                        addReplyError(c,nanerr);
1299
                        goto cleanup;
A
antirez 已提交
1300
                    }
1301 1302
                }

A
antirez 已提交
1303 1304 1305 1306 1307
                /* 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++;
1308
                    updated++;
A
antirez 已提交
1309
                }
A
antirez 已提交
1310 1311
                processed++;
            } else if (!xx) {
A
antirez 已提交
1312 1313
                /* Optimize: check if the element is too large or the list
                 * becomes too long *before* executing zzlInsert. */
1314
                zobj->ptr = zzlInsert(zobj->ptr,ele,score);
A
antirez 已提交
1315
                if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries)
1316
                    zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);
A
antirez 已提交
1317
                if (sdslen(ele->ptr) > server.zset_max_ziplist_value)
1318
                    zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);
1319
                server.dirty++;
1320
                added++;
A
antirez 已提交
1321
                processed++;
1322
            }
1323
        } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
1324 1325 1326 1327
            zset *zs = zobj->ptr;
            zskiplistNode *znode;
            dictEntry *de;

1328 1329
            ele = c->argv[scoreidx+1+j*2] =
                tryObjectEncoding(c->argv[scoreidx+1+j*2]);
A
antirez 已提交
1330 1331
            de = dictFind(zs->dict,ele);
            if (de != NULL) {
A
antirez 已提交
1332
                if (nx) continue;
1333 1334
                curobj = dictGetKey(de);
                curscore = *(double*)dictGetVal(de);
A
antirez 已提交
1335 1336 1337 1338 1339 1340 1341

                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. */
1342
                        goto cleanup;
A
antirez 已提交
1343
                    }
1344 1345
                }

A
antirez 已提交
1346 1347 1348 1349
                /* 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) {
1350
                    redisAssertWithInfo(c,curobj,zslDelete(zs->zsl,curscore,curobj));
A
antirez 已提交
1351 1352
                    znode = zslInsert(zs->zsl,score,curobj);
                    incrRefCount(curobj); /* Re-inserted in skiplist. */
1353
                    dictGetVal(de) = &znode->score; /* Update score ptr. */
A
antirez 已提交
1354
                    server.dirty++;
1355
                    updated++;
A
antirez 已提交
1356
                }
A
antirez 已提交
1357 1358
                processed++;
            } else if (!xx) {
A
antirez 已提交
1359 1360
                znode = zslInsert(zs->zsl,score,ele);
                incrRefCount(ele); /* Inserted in skiplist. */
A
antirez 已提交
1361
                redisAssertWithInfo(c,NULL,dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
A
antirez 已提交
1362
                incrRefCount(ele); /* Added to dictionary. */
1363
                server.dirty++;
1364
                added++;
A
antirez 已提交
1365
                processed++;
1366 1367
            }
        } else {
A
antirez 已提交
1368
            redisPanic("Unknown sorted set encoding");
1369 1370
        }
    }
A
antirez 已提交
1371 1372 1373 1374 1375 1376 1377 1378

reply_to_client:
    if (incr) { /* ZINCRBY or INCR option. */
        if (processed)
            addReplyDouble(c,score);
        else
            addReply(c,shared.nullbulk);
    } else { /* ZADD. */
A
antirez 已提交
1379
        addReplyLongLong(c,ch ? added+updated : added);
A
antirez 已提交
1380
    }
1381 1382 1383 1384 1385

cleanup:
    zfree(scores);
    if (added || updated) {
        signalModifiedKey(c->db,key);
1386 1387
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
            incr ? "zincr" : "zadd", key, c->db->id);
1388
    }
1389 1390
}

1391
void zaddCommand(client *c) {
1392
    zaddGenericCommand(c,ZADD_NONE);
1393 1394
}

1395
void zincrbyCommand(client *c) {
1396
    zaddGenericCommand(c,ZADD_INCR);
1397 1398
}

1399
void zremCommand(client *c) {
P
Pieter Noordhuis 已提交
1400 1401
    robj *key = c->argv[1];
    robj *zobj;
1402
    int deleted = 0, keyremoved = 0, j;
P
Pieter Noordhuis 已提交
1403 1404

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

1407
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
P
Pieter Noordhuis 已提交
1408 1409
        unsigned char *eptr;

A
antirez 已提交
1410 1411 1412 1413 1414 1415
        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);
Z
zionwu 已提交
1416
                    keyremoved = 1;
A
antirez 已提交
1417 1418 1419
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1420
        }
1421
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
P
Pieter Noordhuis 已提交
1422 1423 1424 1425
        zset *zs = zobj->ptr;
        dictEntry *de;
        double score;

A
antirez 已提交
1426 1427 1428 1429 1430 1431
        for (j = 2; j < c->argc; j++) {
            de = dictFind(zs->dict,c->argv[j]);
            if (de != NULL) {
                deleted++;

                /* Delete from the skiplist */
1432
                score = *(double*)dictGetVal(de);
1433
                redisAssertWithInfo(c,c->argv[j],zslDelete(zs->zsl,score,c->argv[j]));
A
antirez 已提交
1434 1435 1436 1437 1438 1439

                /* 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);
Z
zionwu 已提交
1440
                    keyremoved = 1;
A
antirez 已提交
1441 1442 1443
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1444 1445 1446
        }
    } else {
        redisPanic("Unknown sorted set encoding");
1447 1448
    }

A
antirez 已提交
1449
    if (deleted) {
1450 1451 1452
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,"zrem",key,c->db->id);
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
A
antirez 已提交
1453 1454 1455 1456
        signalModifiedKey(c->db,key);
        server.dirty += deleted;
    }
    addReplyLongLong(c,deleted);
1457 1458
}

1459 1460 1461 1462
/* Implements ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX commands. */
#define ZRANGE_RANK 0
#define ZRANGE_SCORE 1
#define ZRANGE_LEX 2
1463
void zremrangeGenericCommand(client *c, int rangetype) {
1464 1465
    robj *key = c->argv[1];
    robj *zobj;
1466
    int keyremoved = 0;
1467
    unsigned long deleted = 0;
1468
    zrangespec range;
A
antirez 已提交
1469
    zlexrangespec lexrange;
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    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 已提交
1482 1483 1484 1485 1486
    } 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;
        }
1487
    }
1488

1489
    /* Step 2: Lookup & range sanity checks if needed. */
1490
    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1491
        checkType(c,zobj,OBJ_ZSET)) goto cleanup;
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
    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);
1504
            goto cleanup;
1505 1506 1507 1508 1509
        }
        if (end >= llen) end = llen-1;
    }

    /* Step 3: Perform the range deletion operation. */
1510
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
1511 1512 1513 1514 1515
        switch(rangetype) {
        case ZRANGE_RANK:
            zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted);
            break;
        case ZRANGE_SCORE:
1516
            zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,&range,&deleted);
1517
            break;
A
antirez 已提交
1518 1519 1520
        case ZRANGE_LEX:
            zobj->ptr = zzlDeleteRangeByLex(zobj->ptr,&lexrange,&deleted);
            break;
1521
        }
1522 1523 1524 1525
        if (zzlLength(zobj->ptr) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1526
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
1527
        zset *zs = zobj->ptr;
1528 1529 1530 1531 1532
        switch(rangetype) {
        case ZRANGE_RANK:
            deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
            break;
        case ZRANGE_SCORE:
1533
            deleted = zslDeleteRangeByScore(zs->zsl,&range,zs->dict);
1534
            break;
A
antirez 已提交
1535 1536 1537
        case ZRANGE_LEX:
            deleted = zslDeleteRangeByLex(zs->zsl,&lexrange,zs->dict);
            break;
1538
        }
1539
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1540 1541 1542 1543
        if (dictSize(zs->dict) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1544 1545 1546
    } else {
        redisPanic("Unknown sorted set encoding");
    }
1547

1548
    /* Step 4: Notifications and reply. */
1549
    if (deleted) {
1550
        char *event[3] = {"zremrangebyrank","zremrangebyscore","zremrangebylex"};
1551
        signalModifiedKey(c->db,key);
1552
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,event[rangetype],key,c->db->id);
1553 1554
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
1555
    }
1556 1557
    server.dirty += deleted;
    addReplyLongLong(c,deleted);
1558 1559 1560

cleanup:
    if (rangetype == ZRANGE_LEX) zslFreeLexRange(&lexrange);
1561 1562
}

1563
void zremrangebyrankCommand(client *c) {
1564 1565
    zremrangeGenericCommand(c,ZRANGE_RANK);
}
1566

1567
void zremrangebyscoreCommand(client *c) {
1568
    zremrangeGenericCommand(c,ZRANGE_SCORE);
1569 1570
}

1571
void zremrangebylexCommand(client *c) {
A
antirez 已提交
1572 1573 1574
    zremrangeGenericCommand(c,ZRANGE_LEX);
}

1575
typedef struct {
1576 1577 1578
    robj *subject;
    int type; /* Set, sorted set */
    int encoding;
1579
    double weight;
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 1605 1606

    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;
1607 1608
} zsetopsrc;

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

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

1638
    if (op->type == OBJ_SET) {
1639
        iterset *it = &op->iter.set;
1640
        if (op->encoding == OBJ_ENCODING_INTSET) {
1641 1642
            it->is.is = op->subject->ptr;
            it->is.ii = 0;
1643
        } else if (op->encoding == OBJ_ENCODING_HT) {
1644 1645 1646 1647 1648 1649
            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");
        }
1650
    } else if (op->type == OBJ_ZSET) {
1651
        iterzset *it = &op->iter.zset;
1652
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1653 1654 1655 1656 1657 1658
            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);
            }
1659
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
            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;

1674
    if (op->type == OBJ_SET) {
1675
        iterset *it = &op->iter.set;
1676
        if (op->encoding == OBJ_ENCODING_INTSET) {
1677
            REDIS_NOTUSED(it); /* skip */
1678
        } else if (op->encoding == OBJ_ENCODING_HT) {
1679 1680 1681 1682
            dictReleaseIterator(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
1683
    } else if (op->type == OBJ_ZSET) {
1684
        iterzset *it = &op->iter.zset;
1685
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1686
            REDIS_NOTUSED(it); /* skip */
1687
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
            REDIS_NOTUSED(it); /* skip */
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

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

1701 1702
    if (op->type == OBJ_SET) {
        if (op->encoding == OBJ_ENCODING_INTSET) {
1703
            return intsetLen(op->subject->ptr);
1704
        } else if (op->encoding == OBJ_ENCODING_HT) {
1705 1706
            dict *ht = op->subject->ptr;
            return dictSize(ht);
1707 1708 1709
        } else {
            redisPanic("Unknown set encoding");
        }
1710 1711
    } else if (op->type == OBJ_ZSET) {
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1712
            return zzlLength(op->subject->ptr);
1713
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1714 1715
            zset *zs = op->subject->ptr;
            return zs->zsl->length;
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
        } 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 已提交
1734
    memset(val,0,sizeof(zsetopval));
1735

1736
    if (op->type == OBJ_SET) {
1737
        iterset *it = &op->iter.set;
1738
        if (op->encoding == OBJ_ENCODING_INTSET) {
1739
            int64_t ell;
A
antirez 已提交
1740 1741

            if (!intsetGet(it->is.is,it->is.ii,&ell))
1742
                return 0;
1743
            val->ell = ell;
1744 1745 1746 1747
            val->score = 1.0;

            /* Move to next element. */
            it->is.ii++;
1748
        } else if (op->encoding == OBJ_ENCODING_HT) {
1749 1750
            if (it->ht.de == NULL)
                return 0;
1751
            val->ele = dictGetKey(it->ht.de);
1752 1753 1754 1755 1756 1757 1758
            val->score = 1.0;

            /* Move to next element. */
            it->ht.de = dictNext(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
1759
    } else if (op->type == OBJ_ZSET) {
1760
        iterzset *it = &op->iter.zset;
1761
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1762 1763 1764 1765 1766 1767 1768 1769
            /* 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);
1770
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
            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) {
1792
            if (val->ele->encoding == OBJ_ENCODING_INT) {
1793 1794
                val->ell = (long)val->ele->ptr;
                val->flags |= OPVAL_VALID_LL;
1795
            } else if (sdsEncodedObject(val->ele)) {
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
                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) {
1827
            if (val->ele->encoding == OBJ_ENCODING_INT) {
1828 1829
                val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),(long)val->ele->ptr);
                val->estr = val->_buf;
1830
            } else if (sdsEncodedObject(val->ele)) {
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
                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;

1850 1851
    if (op->type == OBJ_SET) {
        if (op->encoding == OBJ_ENCODING_INTSET) {
1852 1853 1854
            if (zuiLongLongFromValue(val) &&
                intsetFind(op->subject->ptr,val->ell))
            {
1855 1856 1857 1858 1859
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
1860
        } else if (op->encoding == OBJ_ENCODING_HT) {
1861
            dict *ht = op->subject->ptr;
1862
            zuiObjectFromValue(val);
1863
            if (dictFind(ht,val->ele) != NULL) {
1864 1865 1866 1867 1868 1869 1870 1871
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else {
            redisPanic("Unknown set encoding");
        }
1872
    } else if (op->type == OBJ_ZSET) {
1873 1874
        zuiObjectFromValue(val);

1875
        if (op->encoding == OBJ_ENCODING_ZIPLIST) {
1876
            if (zzlFind(op->subject->ptr,val->ele,score) != NULL) {
1877 1878 1879 1880 1881
                /* Score is already set by zzlFind. */
                return 1;
            } else {
                return 0;
            }
1882
        } else if (op->encoding == OBJ_ENCODING_SKIPLIST) {
1883
            zset *zs = op->subject->ptr;
1884
            dictEntry *de;
1885
            if ((de = dictFind(zs->dict,val->ele)) != NULL) {
1886
                *score = *(double*)dictGetVal(de);
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
                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);
1901 1902 1903 1904 1905
}

#define REDIS_AGGR_SUM 1
#define REDIS_AGGR_MIN 2
#define REDIS_AGGR_MAX 3
1906
#define zunionInterDictValue(_e) (dictGetVal(_e) == NULL ? 1.0 : *(double*)dictGetVal(_e))
1907 1908 1909 1910

inline static void zunionInterAggregate(double *target, double val, int aggregate) {
    if (aggregate == REDIS_AGGR_SUM) {
        *target = *target + val;
1911 1912 1913 1914
        /* 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;
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
    } 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");
    }
}

1925
void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
1926 1927
    int i, j;
    long setnum;
1928 1929
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
1930 1931
    zsetopval zval;
    robj *tmp;
1932
    unsigned int maxelelen = 0;
1933 1934
    robj *dstobj;
    zset *dstzset;
1935
    zskiplistNode *znode;
1936
    int touched = 0;
1937 1938

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

1942
    if (setnum < 1) {
1943 1944
        addReplyError(c,
            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1945 1946 1947 1948
        return;
    }

    /* test if the expected number of keys would overflow */
1949
    if (setnum > c->argc-3) {
1950 1951 1952 1953 1954
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
1955
    src = zcalloc(sizeof(zsetopsrc) * setnum);
1956 1957
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
1958
        if (obj != NULL) {
1959
            if (obj->type != OBJ_ZSET && obj->type != OBJ_SET) {
1960 1961 1962 1963
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
1964 1965 1966 1967 1968 1969

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

1972
        /* Default all weights to 1. */
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
        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--) {
1984
                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
1985
                            "weight value is not a float") != REDIS_OK)
1986 1987
                    {
                        zfree(src);
1988
                        return;
1989
                    }
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
                }
            } 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 */
2015
    qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality);
2016 2017 2018

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;
2019
    memset(&zval, 0, sizeof(zval));
2020 2021

    if (op == REDIS_OP_INTER) {
2022 2023 2024 2025
        /* 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. */
2026
            zuiInitIterator(&src[0]);
2027
            while (zuiNext(&src[0],&zval)) {
2028
                double score, value;
2029

2030
                score = src[0].weight * zval.score;
2031 2032
                if (isnan(score)) score = 0;

2033
                for (j = 1; j < setnum; j++) {
A
antirez 已提交
2034
                    /* It is not safe to access the zset we are
2035
                     * iterating, so explicitly check for equal object. */
2036 2037 2038 2039
                    if (src[j].subject == src[0].subject) {
                        value = zval.score*src[j].weight;
                        zunionInterAggregate(&score,value,aggregate);
                    } else if (zuiFind(&src[j],&zval,&value)) {
2040
                        value *= src[j].weight;
2041
                        zunionInterAggregate(&score,value,aggregate);
2042 2043 2044 2045 2046
                    } else {
                        break;
                    }
                }

2047
                /* Only continue when present in every input. */
2048
                if (j == setnum) {
2049 2050 2051 2052 2053
                    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 */
2054

2055
                    if (sdsEncodedObject(tmp)) {
2056 2057
                        if (sdslen(tmp->ptr) > maxelelen)
                            maxelelen = sdslen(tmp->ptr);
2058
                    }
2059 2060
                }
            }
2061
            zuiClearIterator(&src[0]);
2062 2063
        }
    } else if (op == REDIS_OP_UNION) {
A
antirez 已提交
2064 2065 2066 2067 2068 2069 2070 2071
        dict *accumulator = dictCreate(&setDictType,NULL);
        dictIterator *di;
        dictEntry *de;
        double score;

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

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

2080
            zuiInitIterator(&src[i]);
2081
            while (zuiNext(&src[i],&zval)) {
A
antirez 已提交
2082
                /* Initialize value */
2083
                score = src[i].weight * zval.score;
2084
                if (isnan(score)) score = 0;
2085

A
antirez 已提交
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
                /* Search for this element in the accumulating dictionary. */
                de = dictFind(accumulator,zuiObjectFromValue(&zval));
                /* If we don't have it, we need to create a new entry. */
                if (de == NULL) {
                    tmp = zuiObjectFromValue(&zval);
                    /* Remember the longest single element encountered,
                     * to understand if it's possible to convert to ziplist
                     * at the end. */
                    if (sdsEncodedObject(tmp)) {
                        if (sdslen(tmp->ptr) > maxelelen)
                            maxelelen = sdslen(tmp->ptr);
2097
                    }
A
antirez 已提交
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
                    /* Add the element with its initial score. */
                    de = dictAddRaw(accumulator,tmp);
                    incrRefCount(tmp);
                    dictSetDoubleVal(de,score);
                } else {
                    /* Update the score with the score of the new instance
                     * of the element found in the current sorted set.
                     *
                     * Here we access directly the dictEntry double
                     * value inside the union as it is a big speedup
                     * compared to using the getDouble/setDouble API. */
                    zunionInterAggregate(&de->v.d,score,aggregate);
2110
                }
2111
            }
2112
            zuiClearIterator(&src[i]);
2113
        }
A
antirez 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

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

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

        while((de = dictNext(di)) != NULL) {
            robj *ele = dictGetKey(de);
            score = dictGetDoubleVal(de);
            znode = zslInsert(dstzset->zsl,score,ele);
            incrRefCount(ele); /* added to skiplist */
            dictAdd(dstzset->dict,ele,&znode->score);
            incrRefCount(ele); /* added to dictionary */
        }
        dictReleaseIterator(di);

        /* We can free the accumulator dictionary now. */
        dictRelease(accumulator);
2135
    } else {
2136
        redisPanic("Unknown operator");
2137 2138
    }

2139
    if (dbDelete(c->db,dstkey)) {
2140
        signalModifiedKey(c->db,dstkey);
2141 2142 2143
        touched = 1;
        server.dirty++;
    }
2144
    if (dstzset->zsl->length) {
2145 2146 2147
        /* Convert to ziplist when in limits. */
        if (dstzset->zsl->length <= server.zset_max_ziplist_entries &&
            maxelelen <= server.zset_max_ziplist_value)
2148
                zsetConvert(dstobj,OBJ_ENCODING_ZIPLIST);
2149

2150
        dbAdd(c->db,dstkey,dstobj);
2151
        addReplyLongLong(c,zsetLength(dstobj));
2152
        if (!touched) signalModifiedKey(c->db,dstkey);
2153
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
2154 2155
            (op == REDIS_OP_UNION) ? "zunionstore" : "zinterstore",
            dstkey,c->db->id);
A
antirez 已提交
2156
        server.dirty++;
2157 2158
    } else {
        decrRefCount(dstobj);
2159
        addReply(c,shared.czero);
2160 2161
        if (touched)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",dstkey,c->db->id);
2162 2163 2164 2165
    }
    zfree(src);
}

2166
void zunionstoreCommand(client *c) {
2167 2168 2169
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
}

2170
void zinterstoreCommand(client *c) {
2171 2172 2173
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
}

2174
void zrangeGenericCommand(client *c, int reverse) {
2175 2176 2177
    robj *key = c->argv[1];
    robj *zobj;
    int withscores = 0;
2178 2179 2180
    long start;
    long end;
    int llen;
2181
    int rangelen;
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192

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

2193
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
2194
         || checkType(c,zobj,OBJ_ZSET)) return;
2195

2196
    /* Sanitize indexes. */
2197
    llen = zsetLength(zobj);
2198 2199 2200 2201
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

2202 2203
    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
2204 2205 2206 2207 2208 2209 2210 2211
    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 */
2212 2213
    addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);

2214
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
        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);

2226
        redisAssertWithInfo(c,zobj,eptr != NULL);
2227 2228
        sptr = ziplistNext(zl,eptr);

2229
        while (rangelen--) {
2230 2231
            redisAssertWithInfo(c,zobj,eptr != NULL && sptr != NULL);
            redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2232 2233 2234 2235 2236
            if (vstr == NULL)
                addReplyBulkLongLong(c,vlong);
            else
                addReplyBulkCBuffer(c,vstr,vlen);

2237
            if (withscores)
2238 2239
                addReplyDouble(c,zzlGetScore(sptr));

2240 2241 2242 2243
            if (reverse)
                zzlPrev(zl,&eptr,&sptr);
            else
                zzlNext(zl,&eptr,&sptr);
2244 2245
        }

2246
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
        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--) {
2264
            redisAssertWithInfo(c,zobj,ln != NULL);
2265 2266 2267 2268 2269 2270 2271 2272
            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");
2273 2274 2275
    }
}

2276
void zrangeCommand(client *c) {
2277 2278 2279
    zrangeGenericCommand(c,0);
}

2280
void zrevrangeCommand(client *c) {
2281 2282 2283
    zrangeGenericCommand(c,1);
}

2284
/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */
2285
void genericZrangebyscoreCommand(client *c, int reverse) {
2286
    zrangespec range;
2287
    robj *key = c->argv[1];
2288
    robj *zobj;
2289
    long offset = 0, limit = -1;
2290
    int withscores = 0;
2291 2292
    unsigned long rangelen = 0;
    void *replylen = NULL;
2293
    int minidx, maxidx;
2294

2295
    /* Parse the range arguments. */
2296 2297 2298 2299 2300 2301 2302 2303 2304
    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) {
2305
        addReplyError(c,"min or max is not a float");
2306 2307
        return;
    }
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319

    /* 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")) {
2320 2321
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return;
2322 2323 2324 2325 2326 2327
                pos += 3; remaining -= 3;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }
2328
    }
2329 2330

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

2334
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2335 2336 2337 2338 2339 2340
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;
        double score;
2341

2342
        /* If reversed, get the last node in range as starting point. */
2343
        if (reverse) {
2344
            eptr = zzlLastInRange(zl,&range);
2345
        } else {
2346
            eptr = zzlFirstInRange(zl,&range);
2347
        }
2348

2349 2350
        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
2351
            addReply(c, shared.emptymultibulk);
2352 2353
            return;
        }
2354

2355
        /* Get score pointer for the first element. */
2356
        redisAssertWithInfo(c,zobj,eptr != NULL);
2357
        sptr = ziplistNext(zl,eptr);
2358

2359 2360 2361
        /* 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 */
2362
        replylen = addDeferredMultiBulkLength(c);
2363 2364 2365

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2366 2367
        while (eptr && offset--) {
            if (reverse) {
2368
                zzlPrev(zl,&eptr,&sptr);
2369
            } else {
2370
                zzlNext(zl,&eptr,&sptr);
2371 2372
            }
        }
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383

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

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

2387
            rangelen++;
2388 2389 2390 2391 2392 2393 2394 2395
            if (vstr == NULL) {
                addReplyBulkLongLong(c,vlong);
            } else {
                addReplyBulkCBuffer(c,vstr,vlen);
            }

            if (withscores) {
                addReplyDouble(c,score);
2396 2397 2398
            }

            /* Move to next node */
2399
            if (reverse) {
2400
                zzlPrev(zl,&eptr,&sptr);
2401
            } else {
2402
                zzlNext(zl,&eptr,&sptr);
2403
            }
2404
        }
2405
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2406 2407 2408
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
2409

2410
        /* If reversed, get the last node in range as starting point. */
2411
        if (reverse) {
2412
            ln = zslLastInRange(zsl,&range);
2413
        } else {
2414
            ln = zslFirstInRange(zsl,&range);
2415
        }
2416 2417 2418

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
2419
            addReply(c, shared.emptymultibulk);
2420
            return;
2421 2422
        }

2423 2424 2425
        /* 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 */
2426
        replylen = addDeferredMultiBulkLength(c);
2427 2428 2429

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2430 2431 2432 2433 2434 2435 2436
        while (ln && offset--) {
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446

        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++;
2447 2448 2449 2450
            addReplyBulk(c,ln->obj);

            if (withscores) {
                addReplyDouble(c,ln->score);
2451 2452 2453
            }

            /* Move to next node */
2454 2455 2456 2457 2458
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
2459 2460 2461
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2462 2463
    }

2464 2465
    if (withscores) {
        rangelen *= 2;
2466
    }
2467 2468

    setDeferredMultiBulkLength(c, replylen, rangelen);
2469 2470
}

2471
void zrangebyscoreCommand(client *c) {
2472
    genericZrangebyscoreCommand(c,0);
2473 2474
}

2475
void zrevrangebyscoreCommand(client *c) {
2476
    genericZrangebyscoreCommand(c,1);
2477 2478
}

2479
void zcountCommand(client *c) {
2480 2481 2482 2483 2484 2485 2486
    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) {
2487
        addReplyError(c,"min or max is not a float");
2488 2489 2490 2491 2492
        return;
    }

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

2495
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2496 2497 2498 2499 2500
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        double score;

        /* Use the first element in range as the starting point */
2501
        eptr = zzlFirstInRange(zl,&range);
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511

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

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
        score = zzlGetScore(sptr);
2512
        redisAssertWithInfo(c,zobj,zslValueLteMax(score,&range));
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525

        /* 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);
            }
        }
2526
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2527 2528 2529 2530 2531 2532
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2533
        zn = zslFirstInRange(zsl, &range);
2534 2535 2536 2537 2538 2539 2540

        /* 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 */
2541
            zn = zslLastInRange(zsl, &range);
2542 2543 2544 2545 2546 2547 2548 2549 2550

            /* 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 已提交
2551 2552 2553 2554 2555
    }

    addReplyLongLong(c, count);
}

2556
void zlexcountCommand(client *c) {
A
antirez 已提交
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
    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 ||
2570
        checkType(c, zobj, OBJ_ZSET))
2571 2572 2573 2574
    {
        zslFreeLexRange(&range);
        return;
    }
A
antirez 已提交
2575

2576
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
A
antirez 已提交
2577 2578 2579 2580
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;

        /* Use the first element in range as the starting point */
2581
        eptr = zzlFirstInLexRange(zl,&range);
A
antirez 已提交
2582 2583 2584

        /* No "first" element */
        if (eptr == NULL) {
2585
            zslFreeLexRange(&range);
A
antirez 已提交
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
            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);
            }
        }
2604
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
A
antirez 已提交
2605 2606 2607 2608 2609 2610
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2611
        zn = zslFirstInLexRange(zsl, &range);
A
antirez 已提交
2612 2613 2614 2615 2616 2617 2618

        /* 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 */
2619
            zn = zslLastInLexRange(zsl, &range);
A
antirez 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628

            /* 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");
2629 2630
    }

2631
    zslFreeLexRange(&range);
2632
    addReplyLongLong(c, count);
2633 2634
}

2635
/* This command implements ZRANGEBYLEX, ZREVRANGEBYLEX. */
2636
void genericZrangebylexCommand(client *c, int reverse) {
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
    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 {
2671
                zslFreeLexRange(&range);
2672 2673 2674 2675 2676 2677 2678 2679
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* Ok, lookup the key and get the range */
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2680
        checkType(c,zobj,OBJ_ZSET))
2681 2682 2683 2684
    {
        zslFreeLexRange(&range);
        return;
    }
2685

2686
    if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
2687 2688 2689 2690 2691 2692 2693 2694
        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) {
2695
            eptr = zzlLastInLexRange(zl,&range);
2696
        } else {
2697
            eptr = zzlFirstInLexRange(zl,&range);
2698 2699 2700 2701 2702
        }

        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
            addReply(c, shared.emptymultibulk);
2703
            zslFreeLexRange(&range);
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
            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);
            }
        }
2752
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2753 2754 2755 2756 2757 2758
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2759
            ln = zslLastInLexRange(zsl,&range);
2760
        } else {
2761
            ln = zslFirstInLexRange(zsl,&range);
2762 2763 2764 2765 2766
        }

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
            addReply(c, shared.emptymultibulk);
2767
            zslFreeLexRange(&range);
2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807
            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");
    }

2808
    zslFreeLexRange(&range);
2809 2810 2811
    setDeferredMultiBulkLength(c, replylen, rangelen);
}

2812
void zrangebylexCommand(client *c) {
2813 2814 2815
    genericZrangebylexCommand(c,0);
}

2816
void zrevrangebylexCommand(client *c) {
2817 2818 2819
    genericZrangebylexCommand(c,1);
}

2820
void zcardCommand(client *c) {
2821 2822
    robj *key = c->argv[1];
    robj *zobj;
2823

2824
    if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL ||
2825
        checkType(c,zobj,OBJ_ZSET)) return;
2826

2827
    addReplyLongLong(c,zsetLength(zobj));
2828 2829
}

2830
void zscoreCommand(client *c) {
2831 2832 2833
    robj *key = c->argv[1];
    robj *zobj;
    double score;
2834

2835
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
2836
        checkType(c,zobj,OBJ_ZSET)) return;
2837

A
antirez 已提交
2838 2839
    if (zsetScore(zobj,c->argv[2],&score) == REDIS_ERR) {
        addReply(c,shared.nullbulk);
2840
    } else {
A
antirez 已提交
2841
        addReplyDouble(c,score);
2842 2843 2844
    }
}

2845
void zrankGenericCommand(client *c, int reverse) {
2846 2847 2848 2849
    robj *key = c->argv[1];
    robj *ele = c->argv[2];
    robj *zobj;
    unsigned long llen;
2850 2851
    unsigned long rank;

2852
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
2853
        checkType(c,zobj,OBJ_ZSET)) return;
2854
    llen = zsetLength(zobj);
2855

2856 2857
    redisAssertWithInfo(c,ele,sdsEncodedObject(ele));

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

2862
        eptr = ziplistIndex(zl,0);
2863
        redisAssertWithInfo(c,zobj,eptr != NULL);
2864
        sptr = ziplistNext(zl,eptr);
2865
        redisAssertWithInfo(c,zobj,sptr != NULL);
2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879

        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);
2880
        } else {
2881 2882
            addReply(c,shared.nullbulk);
        }
2883
    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
2884 2885 2886 2887 2888
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        dictEntry *de;
        double score;

2889
        ele = c->argv[2];
2890 2891
        de = dictFind(zs->dict,ele);
        if (de != NULL) {
2892
            score = *(double*)dictGetVal(de);
2893
            rank = zslGetRank(zsl,score,ele);
2894
            redisAssertWithInfo(c,ele,rank); /* Existing elements always have a rank. */
2895 2896 2897 2898 2899 2900
            if (reverse)
                addReplyLongLong(c,llen-rank);
            else
                addReplyLongLong(c,rank-1);
        } else {
            addReply(c,shared.nullbulk);
2901 2902
        }
    } else {
2903
        redisPanic("Unknown sorted set encoding");
2904 2905 2906
    }
}

2907
void zrankCommand(client *c) {
2908 2909 2910
    zrankGenericCommand(c, 0);
}

2911
void zrevrankCommand(client *c) {
2912 2913
    zrankGenericCommand(c, 1);
}
A
antirez 已提交
2914

2915
void zscanCommand(client *c) {
A
antirez 已提交
2916
    robj *o;
2917
    unsigned long cursor;
A
antirez 已提交
2918

2919
    if (parseScanCursorOrReply(c,c->argv[2],&cursor) == REDIS_ERR) return;
2920
    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL ||
2921
        checkType(c,o,OBJ_ZSET)) return;
2922
    scanGenericCommand(c,o,cursor);
A
antirez 已提交
2923
}