t_zset.c 92.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 53 54
#include "redis.h"
#include <math.h>

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

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

zskiplist *zslCreate(void) {
    int j;
    zskiplist *zsl;

    zsl = zmalloc(sizeof(*zsl));
    zsl->level = 1;
    zsl->length = 0;
    zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
    for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
74 75
        zsl->header->level[j].forward = NULL;
        zsl->header->level[j].span = 0;
76 77 78 79 80 81 82 83 84 85 86 87
    }
    zsl->header->backward = NULL;
    zsl->tail = NULL;
    return zsl;
}

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

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

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

99 100 101 102
/* Returns a random level for the new skiplist node we are going to create.
 * The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
 * (both inclusive), with a powerlaw-alike distribution where higher
 * levels are less likely to be returned. */
103 104 105 106 107 108 109
int zslRandomLevel(void) {
    int level = 1;
    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
        level += 1;
    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}

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

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

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

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

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

/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
    int i;
    for (i = 0; i < zsl->level; i++) {
170 171 172
        if (update[i]->level[i].forward == x) {
            update[i]->level[i].span += x->level[i].span - 1;
            update[i]->level[i].forward = x->level[i].forward;
173
        } else {
174
            update[i]->level[i].span -= 1;
175 176
        }
    }
177 178
    if (x->level[0].forward) {
        x->level[0].forward->backward = x->backward;
179 180 181
    } else {
        zsl->tail = x->backward;
    }
182
    while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
183 184 185 186 187 188 189 190 191 192 193
        zsl->level--;
    zsl->length--;
}

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

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
194 195 196 197 198
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,obj) < 0)))
            x = x->level[i].forward;
199 200 201 202
        update[i] = x;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
203
    x = x->level[0].forward;
204 205 206 207 208 209 210 211
    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);
}

P
Pieter Noordhuis 已提交
216
static 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 438 439 440 441
    spec->minex = spec->maxex = 0;

    /* Parse the min-max interval. If one of the values is prefixed
     * by the "(" character, it's considered "open". For instance
     * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
     * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
    if (min->encoding == REDIS_ENCODING_INT) {
        spec->min = (long)min->ptr;
    } else {
        if (((char*)min->ptr)[0] == '(') {
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 451 452 453
        }
    }
    if (max->encoding == REDIS_ENCODING_INT) {
        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 520 521 522 523 524 525 526 527 528 529 530 531
    if (min->encoding == REDIS_ENCODING_INT ||
        max->encoding == REDIS_ENCODING_INT) return REDIS_ERR;

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

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 1083
    int length = -1;
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1084
        length = zzlLength(zobj->ptr);
1085
    } else if (zobj->encoding == REDIS_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 1100 1101 1102 1103 1104 1105 1106
    zset *zs;
    zskiplistNode *node, *next;
    robj *ele;
    double score;

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

1107
        if (encoding != REDIS_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 = REDIS_ENCODING_SKIPLIST;
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        unsigned char *zl = ziplistNew();

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

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

        while (node) {
            ele = getDecodedObject(node->obj);
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 1164 1165 1166 1167 1168
        zobj->encoding = REDIS_ENCODING_ZIPLIST;
    } else {
        redisPanic("Unknown sorted set encoding");
    }
}

1169
/*-----------------------------------------------------------------------------
1170
 * Sorted set commands
1171 1172
 *----------------------------------------------------------------------------*/

1173
/* This generic command implements both ZADD and ZINCRBY. */
1174 1175 1176 1177 1178
#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. */
void zaddGenericCommand(redisClient *c, int flags) {
1179
    static char *nanerr = "resulting score is not a number (NaN)";
1180 1181
    robj *key = c->argv[1];
    robj *ele;
1182 1183
    robj *zobj;
    robj *curobj;
1184
    double score = 0, *scores = NULL, curscore = 0.0;
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    int j, elements;
    int added = 0, updated = 0, scoreidx = 0;

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

1205 1206 1207 1208
    /* 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 已提交
1209
        addReply(c,shared.syntaxerr);
1210
        return;
A
antirez 已提交
1211
    }
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    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 已提交
1226 1227 1228 1229 1230 1231

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

A
antirez 已提交
1236
    /* Lookup the key and create the sorted set if does not exist. */
1237 1238
    zobj = lookupKeyWrite(c->db,key);
    if (zobj == NULL) {
1239 1240 1241 1242 1243 1244 1245
        if (server.zset_max_ziplist_entries == 0 ||
            server.zset_max_ziplist_value < sdslen(c->argv[3]->ptr))
        {
            zobj = createZsetObject();
        } else {
            zobj = createZsetZiplistObject();
        }
1246
        dbAdd(c->db,key,zobj);
1247
    } else {
1248
        if (zobj->type != REDIS_ZSET) {
1249
            addReply(c,shared.wrongtypeerr);
1250
            goto cleanup;
1251 1252 1253
        }
    }

A
antirez 已提交
1254 1255 1256 1257 1258 1259 1260
    for (j = 0; j < elements; j++) {
        score = scores[j];

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

            /* Prefer non-encoded element when dealing with ziplists. */
1261
            ele = c->argv[scoreidx+1+j*2];
A
antirez 已提交
1262 1263 1264 1265 1266
            if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
                if (incr) {
                    score += curscore;
                    if (isnan(score)) {
                        addReplyError(c,nanerr);
1267
                        goto cleanup;
A
antirez 已提交
1268
                    }
1269 1270
                }

A
antirez 已提交
1271 1272 1273 1274 1275
                /* 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++;
1276
                    updated++;
A
antirez 已提交
1277 1278 1279 1280
                }
            } else {
                /* Optimize: check if the element is too large or the list
                 * becomes too long *before* executing zzlInsert. */
1281
                zobj->ptr = zzlInsert(zobj->ptr,ele,score);
A
antirez 已提交
1282 1283 1284 1285
                if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries)
                    zsetConvert(zobj,REDIS_ENCODING_SKIPLIST);
                if (sdslen(ele->ptr) > server.zset_max_ziplist_value)
                    zsetConvert(zobj,REDIS_ENCODING_SKIPLIST);
1286
                server.dirty++;
1287
                added++;
1288
            }
A
antirez 已提交
1289 1290 1291 1292 1293
        } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
            zset *zs = zobj->ptr;
            zskiplistNode *znode;
            dictEntry *de;

1294 1295
            ele = c->argv[scoreidx+1+j*2] =
                tryObjectEncoding(c->argv[scoreidx+1+j*2]);
A
antirez 已提交
1296 1297
            de = dictFind(zs->dict,ele);
            if (de != NULL) {
1298 1299
                curobj = dictGetKey(de);
                curscore = *(double*)dictGetVal(de);
A
antirez 已提交
1300 1301 1302 1303 1304 1305 1306

                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. */
1307
                        goto cleanup;
A
antirez 已提交
1308
                    }
1309 1310
                }

A
antirez 已提交
1311 1312 1313 1314
                /* 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) {
1315
                    redisAssertWithInfo(c,curobj,zslDelete(zs->zsl,curscore,curobj));
A
antirez 已提交
1316 1317
                    znode = zslInsert(zs->zsl,score,curobj);
                    incrRefCount(curobj); /* Re-inserted in skiplist. */
1318
                    dictGetVal(de) = &znode->score; /* Update score ptr. */
A
antirez 已提交
1319
                    server.dirty++;
1320
                    updated++;
A
antirez 已提交
1321 1322 1323 1324
                }
            } else {
                znode = zslInsert(zs->zsl,score,ele);
                incrRefCount(ele); /* Inserted in skiplist. */
A
antirez 已提交
1325
                redisAssertWithInfo(c,NULL,dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
A
antirez 已提交
1326
                incrRefCount(ele); /* Added to dictionary. */
1327
                server.dirty++;
1328
                added++;
1329 1330
            }
        } else {
A
antirez 已提交
1331
            redisPanic("Unknown sorted set encoding");
1332 1333
        }
    }
A
antirez 已提交
1334 1335 1336 1337
    if (incr) /* ZINCRBY */
        addReplyDouble(c,score);
    else /* ZADD */
        addReplyLongLong(c,added);
1338 1339 1340 1341 1342

cleanup:
    zfree(scores);
    if (added || updated) {
        signalModifiedKey(c->db,key);
1343 1344
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
            incr ? "zincr" : "zadd", key, c->db->id);
1345
    }
1346 1347 1348
}

void zaddCommand(redisClient *c) {
1349
    zaddGenericCommand(c,ZADD_NONE);
1350 1351 1352
}

void zincrbyCommand(redisClient *c) {
1353
    zaddGenericCommand(c,ZADD_INCR);
1354 1355 1356
}

void zremCommand(redisClient *c) {
P
Pieter Noordhuis 已提交
1357 1358
    robj *key = c->argv[1];
    robj *zobj;
1359
    int deleted = 0, keyremoved = 0, j;
P
Pieter Noordhuis 已提交
1360 1361 1362 1363 1364 1365 1366

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

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

A
antirez 已提交
1367 1368 1369 1370 1371 1372
        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 已提交
1373
                    keyremoved = 1;
A
antirez 已提交
1374 1375 1376
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1377
        }
1378
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
P
Pieter Noordhuis 已提交
1379 1380 1381 1382
        zset *zs = zobj->ptr;
        dictEntry *de;
        double score;

A
antirez 已提交
1383 1384 1385 1386 1387 1388
        for (j = 2; j < c->argc; j++) {
            de = dictFind(zs->dict,c->argv[j]);
            if (de != NULL) {
                deleted++;

                /* Delete from the skiplist */
1389
                score = *(double*)dictGetVal(de);
1390
                redisAssertWithInfo(c,c->argv[j],zslDelete(zs->zsl,score,c->argv[j]));
A
antirez 已提交
1391 1392 1393 1394 1395 1396

                /* 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 已提交
1397
                    keyremoved = 1;
A
antirez 已提交
1398 1399 1400
                    break;
                }
            }
P
Pieter Noordhuis 已提交
1401 1402 1403
        }
    } else {
        redisPanic("Unknown sorted set encoding");
1404 1405
    }

A
antirez 已提交
1406
    if (deleted) {
1407 1408 1409
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,"zrem",key,c->db->id);
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
A
antirez 已提交
1410 1411 1412 1413
        signalModifiedKey(c->db,key);
        server.dirty += deleted;
    }
    addReplyLongLong(c,deleted);
1414 1415
}

1416 1417 1418 1419 1420
/* Implements ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZREMRANGEBYLEX commands. */
#define ZRANGE_RANK 0
#define ZRANGE_SCORE 1
#define ZRANGE_LEX 2
void zremrangeGenericCommand(redisClient *c, int rangetype) {
1421 1422
    robj *key = c->argv[1];
    robj *zobj;
1423
    int keyremoved = 0;
1424
    unsigned long deleted = 0;
1425
    zrangespec range;
A
antirez 已提交
1426
    zlexrangespec lexrange;
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    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 已提交
1439 1440 1441 1442 1443
    } 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;
        }
1444
    }
1445

1446
    /* Step 2: Lookup & range sanity checks if needed. */
1447
    if ((zobj = lookupKeyWriteOrReply(c,key,shared.czero)) == NULL ||
1448
        checkType(c,zobj,REDIS_ZSET)) goto cleanup;
1449

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    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);
1461
            goto cleanup;
1462 1463 1464 1465 1466
        }
        if (end >= llen) end = llen-1;
    }

    /* Step 3: Perform the range deletion operation. */
1467
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
1468 1469 1470 1471 1472
        switch(rangetype) {
        case ZRANGE_RANK:
            zobj->ptr = zzlDeleteRangeByRank(zobj->ptr,start+1,end+1,&deleted);
            break;
        case ZRANGE_SCORE:
1473
            zobj->ptr = zzlDeleteRangeByScore(zobj->ptr,&range,&deleted);
1474
            break;
A
antirez 已提交
1475 1476 1477
        case ZRANGE_LEX:
            zobj->ptr = zzlDeleteRangeByLex(zobj->ptr,&lexrange,&deleted);
            break;
1478
        }
1479 1480 1481 1482
        if (zzlLength(zobj->ptr) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1483
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
1484
        zset *zs = zobj->ptr;
1485 1486 1487 1488 1489
        switch(rangetype) {
        case ZRANGE_RANK:
            deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
            break;
        case ZRANGE_SCORE:
1490
            deleted = zslDeleteRangeByScore(zs->zsl,&range,zs->dict);
1491
            break;
A
antirez 已提交
1492 1493 1494
        case ZRANGE_LEX:
            deleted = zslDeleteRangeByLex(zs->zsl,&lexrange,zs->dict);
            break;
1495
        }
1496
        if (htNeedsResize(zs->dict)) dictResize(zs->dict);
1497 1498 1499 1500
        if (dictSize(zs->dict) == 0) {
            dbDelete(c->db,key);
            keyremoved = 1;
        }
1501 1502 1503
    } else {
        redisPanic("Unknown sorted set encoding");
    }
1504

1505
    /* Step 4: Notifications and reply. */
1506
    if (deleted) {
1507
        char *event[3] = {"zremrangebyrank","zremrangebyscore","zremrangebylex"};
1508
        signalModifiedKey(c->db,key);
1509
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,event[rangetype],key,c->db->id);
1510 1511
        if (keyremoved)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",key,c->db->id);
1512
    }
1513 1514
    server.dirty += deleted;
    addReplyLongLong(c,deleted);
1515 1516 1517

cleanup:
    if (rangetype == ZRANGE_LEX) zslFreeLexRange(&lexrange);
1518 1519 1520
}

void zremrangebyrankCommand(redisClient *c) {
1521 1522
    zremrangeGenericCommand(c,ZRANGE_RANK);
}
1523

1524 1525
void zremrangebyscoreCommand(redisClient *c) {
    zremrangeGenericCommand(c,ZRANGE_SCORE);
1526 1527
}

A
antirez 已提交
1528 1529 1530 1531
void zremrangebylexCommand(redisClient *c) {
    zremrangeGenericCommand(c,ZRANGE_LEX);
}

1532
typedef struct {
1533 1534 1535
    robj *subject;
    int type; /* Set, sorted set */
    int encoding;
1536
    double weight;
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

    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;
1564 1565
} zsetopsrc;

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615

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

/* Store value retrieved from the iterator. */
typedef struct {
    int flags;
    unsigned char _buf[32]; /* Private buffer. */
    robj *ele;
    unsigned char *estr;
    unsigned int elen;
    long long ell;
    double score;
} zsetopval;

typedef union _iterset iterset;
typedef union _iterzset iterzset;

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

    if (op->type == REDIS_SET) {
        iterset *it = &op->iter.set;
        if (op->encoding == REDIS_ENCODING_INTSET) {
            it->is.is = op->subject->ptr;
            it->is.ii = 0;
        } else if (op->encoding == REDIS_ENCODING_HT) {
            it->ht.dict = op->subject->ptr;
            it->ht.di = dictGetIterator(op->subject->ptr);
            it->ht.de = dictNext(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        iterzset *it = &op->iter.zset;
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
            it->zl.zl = op->subject->ptr;
            it->zl.eptr = ziplistIndex(it->zl.zl,0);
            if (it->zl.eptr != NULL) {
                it->zl.sptr = ziplistNext(it->zl.zl,it->zl.eptr);
                redisAssert(it->zl.sptr != NULL);
            }
1616
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
            it->sl.zs = op->subject->ptr;
            it->sl.node = it->sl.zs->zsl->header->level[0].forward;
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

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

    if (op->type == REDIS_SET) {
        iterset *it = &op->iter.set;
        if (op->encoding == REDIS_ENCODING_INTSET) {
            REDIS_NOTUSED(it); /* skip */
        } else if (op->encoding == REDIS_ENCODING_HT) {
            dictReleaseIterator(it->ht.di);
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        iterzset *it = &op->iter.zset;
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
            REDIS_NOTUSED(it); /* skip */
1644
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
            REDIS_NOTUSED(it); /* skip */
        } else {
            redisPanic("Unknown sorted set encoding");
        }
    } else {
        redisPanic("Unsupported type");
    }
}

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

    if (op->type == REDIS_SET) {
        if (op->encoding == REDIS_ENCODING_INTSET) {
1660
            return intsetLen(op->subject->ptr);
1661
        } else if (op->encoding == REDIS_ENCODING_HT) {
1662 1663
            dict *ht = op->subject->ptr;
            return dictSize(ht);
1664 1665 1666 1667 1668
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1669
            return zzlLength(op->subject->ptr);
1670
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1671 1672
            zset *zs = op->subject->ptr;
            return zs->zsl->length;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
        } 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 已提交
1691
    memset(val,0,sizeof(zsetopval));
1692 1693 1694 1695

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

            if (!intsetGet(it->is.is,it->is.ii,&ell))
1699
                return 0;
1700
            val->ell = ell;
1701 1702 1703 1704 1705 1706 1707
            val->score = 1.0;

            /* Move to next element. */
            it->is.ii++;
        } else if (op->encoding == REDIS_ENCODING_HT) {
            if (it->ht.de == NULL)
                return 0;
1708
            val->ele = dictGetKey(it->ht.de);
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
            val->score = 1.0;

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

            /* Move to next element. */
            zzlNext(it->zl.zl,&it->zl.eptr,&it->zl.sptr);
1727
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
            if (it->sl.node == NULL)
                return 0;
            val->ele = it->sl.node->obj;
            val->score = it->sl.node->score;

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

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

        if (val->ele != NULL) {
            if (val->ele->encoding == REDIS_ENCODING_INT) {
                val->ell = (long)val->ele->ptr;
                val->flags |= OPVAL_VALID_LL;
1752
            } else if (sdsEncodedObject(val->ele)) {
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
                if (string2ll(val->ele->ptr,sdslen(val->ele->ptr),&val->ell))
                    val->flags |= OPVAL_VALID_LL;
            } else {
                redisPanic("Unsupported element encoding");
            }
        } else if (val->estr != NULL) {
            if (string2ll((char*)val->estr,val->elen,&val->ell))
                val->flags |= OPVAL_VALID_LL;
        } else {
            /* The long long was already set, flag as valid. */
            val->flags |= OPVAL_VALID_LL;
        }
    }
    return val->flags & OPVAL_VALID_LL;
}

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

int zuiBufferFromValue(zsetopval *val) {
    if (val->estr == NULL) {
        if (val->ele != NULL) {
            if (val->ele->encoding == REDIS_ENCODING_INT) {
                val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),(long)val->ele->ptr);
                val->estr = val->_buf;
1787
            } else if (sdsEncodedObject(val->ele)) {
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
                val->elen = sdslen(val->ele->ptr);
                val->estr = val->ele->ptr;
            } else {
                redisPanic("Unsupported element encoding");
            }
        } else {
            val->elen = ll2string((char*)val->_buf,sizeof(val->_buf),val->ell);
            val->estr = val->_buf;
        }
    }
    return 1;
}

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

    if (op->type == REDIS_SET) {
        if (op->encoding == REDIS_ENCODING_INTSET) {
1809 1810 1811
            if (zuiLongLongFromValue(val) &&
                intsetFind(op->subject->ptr,val->ell))
            {
1812 1813 1814 1815 1816 1817
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else if (op->encoding == REDIS_ENCODING_HT) {
1818
            dict *ht = op->subject->ptr;
1819
            zuiObjectFromValue(val);
1820
            if (dictFind(ht,val->ele) != NULL) {
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
                *score = 1.0;
                return 1;
            } else {
                return 0;
            }
        } else {
            redisPanic("Unknown set encoding");
        }
    } else if (op->type == REDIS_ZSET) {
        zuiObjectFromValue(val);

        if (op->encoding == REDIS_ENCODING_ZIPLIST) {
1833
            if (zzlFind(op->subject->ptr,val->ele,score) != NULL) {
1834 1835 1836 1837 1838
                /* Score is already set by zzlFind. */
                return 1;
            } else {
                return 0;
            }
1839
        } else if (op->encoding == REDIS_ENCODING_SKIPLIST) {
1840
            zset *zs = op->subject->ptr;
1841
            dictEntry *de;
1842
            if ((de = dictFind(zs->dict,val->ele)) != NULL) {
1843
                *score = *(double*)dictGetVal(de);
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
                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);
1858 1859 1860 1861 1862
}

#define REDIS_AGGR_SUM 1
#define REDIS_AGGR_MIN 2
#define REDIS_AGGR_MAX 3
1863
#define zunionInterDictValue(_e) (dictGetVal(_e) == NULL ? 1.0 : *(double*)dictGetVal(_e))
1864 1865 1866 1867

inline static void zunionInterAggregate(double *target, double val, int aggregate) {
    if (aggregate == REDIS_AGGR_SUM) {
        *target = *target + val;
1868 1869 1870 1871
        /* 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;
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
    } else if (aggregate == REDIS_AGGR_MIN) {
        *target = val < *target ? val : *target;
    } else if (aggregate == REDIS_AGGR_MAX) {
        *target = val > *target ? val : *target;
    } else {
        /* safety net */
        redisPanic("Unknown ZUNION/INTER aggregate type");
    }
}

void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
1883 1884
    int i, j;
    long setnum;
1885 1886
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
1887 1888
    zsetopval zval;
    robj *tmp;
1889
    unsigned int maxelelen = 0;
1890 1891
    robj *dstobj;
    zset *dstzset;
1892
    zskiplistNode *znode;
1893
    int touched = 0;
1894 1895

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

1899
    if (setnum < 1) {
1900 1901
        addReplyError(c,
            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
1902 1903 1904 1905
        return;
    }

    /* test if the expected number of keys would overflow */
1906
    if (setnum > c->argc-3) {
1907 1908 1909 1910 1911
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
1912
    src = zcalloc(sizeof(zsetopsrc) * setnum);
1913 1914
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
1915 1916
        if (obj != NULL) {
            if (obj->type != REDIS_ZSET && obj->type != REDIS_SET) {
1917 1918 1919 1920
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
1921 1922 1923 1924 1925 1926

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

1929
        /* Default all weights to 1. */
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
        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--) {
1941
                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
1942
                            "weight value is not a float") != REDIS_OK)
1943 1944
                    {
                        zfree(src);
1945
                        return;
1946
                    }
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
                }
            } 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 */
1972
    qsort(src,setnum,sizeof(zsetopsrc),zuiCompareByCardinality);
1973 1974 1975

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;
1976
    memset(&zval, 0, sizeof(zval));
1977 1978

    if (op == REDIS_OP_INTER) {
1979 1980 1981 1982
        /* 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. */
1983
            zuiInitIterator(&src[0]);
1984
            while (zuiNext(&src[0],&zval)) {
1985
                double score, value;
1986

1987
                score = src[0].weight * zval.score;
1988 1989
                if (isnan(score)) score = 0;

1990
                for (j = 1; j < setnum; j++) {
A
antirez 已提交
1991
                    /* It is not safe to access the zset we are
1992
                     * iterating, so explicitly check for equal object. */
1993 1994 1995 1996
                    if (src[j].subject == src[0].subject) {
                        value = zval.score*src[j].weight;
                        zunionInterAggregate(&score,value,aggregate);
                    } else if (zuiFind(&src[j],&zval,&value)) {
1997
                        value *= src[j].weight;
1998
                        zunionInterAggregate(&score,value,aggregate);
1999 2000 2001 2002 2003
                    } else {
                        break;
                    }
                }

2004
                /* Only continue when present in every input. */
2005
                if (j == setnum) {
2006 2007 2008 2009 2010
                    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 */
2011

2012
                    if (sdsEncodedObject(tmp)) {
2013 2014
                        if (sdslen(tmp->ptr) > maxelelen)
                            maxelelen = sdslen(tmp->ptr);
2015
                    }
2016 2017
                }
            }
2018
            zuiClearIterator(&src[0]);
2019 2020
        }
    } else if (op == REDIS_OP_UNION) {
A
antirez 已提交
2021 2022 2023 2024 2025 2026 2027 2028
        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. */
2029
            dictExpand(accumulator,zuiLength(&src[setnum-1]));
A
antirez 已提交
2030 2031 2032 2033
        }

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

2037
            zuiInitIterator(&src[i]);
2038
            while (zuiNext(&src[i],&zval)) {
A
antirez 已提交
2039
                /* Initialize value */
2040
                score = src[i].weight * zval.score;
2041
                if (isnan(score)) score = 0;
2042

A
antirez 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
                /* 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);
2054
                    }
A
antirez 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
                    /* 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);
2067
                }
2068
            }
2069
            zuiClearIterator(&src[i]);
2070
        }
A
antirez 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091

        /* 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);
2092
    } else {
2093
        redisPanic("Unknown operator");
2094 2095
    }

2096
    if (dbDelete(c->db,dstkey)) {
2097
        signalModifiedKey(c->db,dstkey);
2098 2099 2100
        touched = 1;
        server.dirty++;
    }
2101
    if (dstzset->zsl->length) {
2102 2103 2104
        /* Convert to ziplist when in limits. */
        if (dstzset->zsl->length <= server.zset_max_ziplist_entries &&
            maxelelen <= server.zset_max_ziplist_value)
2105
                zsetConvert(dstobj,REDIS_ENCODING_ZIPLIST);
2106

2107
        dbAdd(c->db,dstkey,dstobj);
2108
        addReplyLongLong(c,zsetLength(dstobj));
2109
        if (!touched) signalModifiedKey(c->db,dstkey);
2110
        notifyKeyspaceEvent(REDIS_NOTIFY_ZSET,
2111 2112
            (op == REDIS_OP_UNION) ? "zunionstore" : "zinterstore",
            dstkey,c->db->id);
A
antirez 已提交
2113
        server.dirty++;
2114 2115
    } else {
        decrRefCount(dstobj);
2116
        addReply(c,shared.czero);
2117 2118
        if (touched)
            notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",dstkey,c->db->id);
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
    }
    zfree(src);
}

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

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

void zrangeGenericCommand(redisClient *c, int reverse) {
2132 2133 2134
    robj *key = c->argv[1];
    robj *zobj;
    int withscores = 0;
2135 2136 2137
    long start;
    long end;
    int llen;
2138
    int rangelen;
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149

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

2150 2151
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL
         || checkType(c,zobj,REDIS_ZSET)) return;
2152

2153
    /* Sanitize indexes. */
2154
    llen = zsetLength(zobj);
2155 2156 2157 2158
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

2159 2160
    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
2161 2162 2163 2164 2165 2166 2167 2168
    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 */
2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
    addReplyMultiBulkLen(c, withscores ? (rangelen*2) : rangelen);

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

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

2183
        redisAssertWithInfo(c,zobj,eptr != NULL);
2184 2185
        sptr = ziplistNext(zl,eptr);

2186
        while (rangelen--) {
2187 2188
            redisAssertWithInfo(c,zobj,eptr != NULL && sptr != NULL);
            redisAssertWithInfo(c,zobj,ziplistGet(eptr,&vstr,&vlen,&vlong));
2189 2190 2191 2192 2193
            if (vstr == NULL)
                addReplyBulkLongLong(c,vlong);
            else
                addReplyBulkCBuffer(c,vstr,vlen);

2194
            if (withscores)
2195 2196
                addReplyDouble(c,zzlGetScore(sptr));

2197 2198 2199 2200
            if (reverse)
                zzlPrev(zl,&eptr,&sptr);
            else
                zzlNext(zl,&eptr,&sptr);
2201 2202
        }

2203
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
        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--) {
2221
            redisAssertWithInfo(c,zobj,ln != NULL);
2222 2223 2224 2225 2226 2227 2228 2229
            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");
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    }
}

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

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

2241 2242
/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE. */
void genericZrangebyscoreCommand(redisClient *c, int reverse) {
2243
    zrangespec range;
2244
    robj *key = c->argv[1];
2245
    robj *zobj;
2246
    long offset = 0, limit = -1;
2247
    int withscores = 0;
2248 2249
    unsigned long rangelen = 0;
    void *replylen = NULL;
2250
    int minidx, maxidx;
2251

2252
    /* Parse the range arguments. */
2253 2254 2255 2256 2257 2258 2259 2260 2261
    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) {
2262
        addReplyError(c,"min or max is not a float");
2263 2264
        return;
    }
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276

    /* 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")) {
2277 2278
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return;
2279 2280 2281 2282 2283 2284
                pos += 3; remaining -= 3;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }
2285
    }
2286 2287

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

2291 2292 2293 2294 2295 2296 2297
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
        unsigned char *zl = zobj->ptr;
        unsigned char *eptr, *sptr;
        unsigned char *vstr;
        unsigned int vlen;
        long long vlong;
        double score;
2298

2299
        /* If reversed, get the last node in range as starting point. */
2300
        if (reverse) {
2301
            eptr = zzlLastInRange(zl,&range);
2302
        } else {
2303
            eptr = zzlFirstInRange(zl,&range);
2304
        }
2305

2306 2307
        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
2308
            addReply(c, shared.emptymultibulk);
2309 2310
            return;
        }
2311

2312
        /* Get score pointer for the first element. */
2313
        redisAssertWithInfo(c,zobj,eptr != NULL);
2314
        sptr = ziplistNext(zl,eptr);
2315

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

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2323 2324
        while (eptr && offset--) {
            if (reverse) {
2325
                zzlPrev(zl,&eptr,&sptr);
2326
            } else {
2327
                zzlNext(zl,&eptr,&sptr);
2328 2329
            }
        }
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340

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

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

2344
            rangelen++;
2345 2346 2347 2348 2349 2350 2351 2352
            if (vstr == NULL) {
                addReplyBulkLongLong(c,vlong);
            } else {
                addReplyBulkCBuffer(c,vstr,vlen);
            }

            if (withscores) {
                addReplyDouble(c,score);
2353 2354 2355
            }

            /* Move to next node */
2356
            if (reverse) {
2357
                zzlPrev(zl,&eptr,&sptr);
2358
            } else {
2359
                zzlNext(zl,&eptr,&sptr);
2360
            }
2361
        }
2362
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2363 2364 2365
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;
2366

2367
        /* If reversed, get the last node in range as starting point. */
2368
        if (reverse) {
2369
            ln = zslLastInRange(zsl,&range);
2370
        } else {
2371
            ln = zslFirstInRange(zsl,&range);
2372
        }
2373 2374 2375

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
2376
            addReply(c, shared.emptymultibulk);
2377
            return;
2378 2379
        }

2380 2381 2382
        /* 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 */
2383
        replylen = addDeferredMultiBulkLength(c);
2384 2385 2386

        /* If there is an offset, just traverse the number of elements without
         * checking the score because that is done in the next loop. */
2387 2388 2389 2390 2391 2392 2393
        while (ln && offset--) {
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
        }
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403

        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++;
2404 2405 2406 2407
            addReplyBulk(c,ln->obj);

            if (withscores) {
                addReplyDouble(c,ln->score);
2408 2409 2410
            }

            /* Move to next node */
2411 2412 2413 2414 2415
            if (reverse) {
                ln = ln->backward;
            } else {
                ln = ln->level[0].forward;
            }
2416 2417 2418
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2419 2420
    }

2421 2422
    if (withscores) {
        rangelen *= 2;
2423
    }
2424 2425

    setDeferredMultiBulkLength(c, replylen, rangelen);
2426 2427 2428
}

void zrangebyscoreCommand(redisClient *c) {
2429
    genericZrangebyscoreCommand(c,0);
2430 2431 2432
}

void zrevrangebyscoreCommand(redisClient *c) {
2433
    genericZrangebyscoreCommand(c,1);
2434 2435 2436
}

void zcountCommand(redisClient *c) {
2437 2438 2439 2440 2441 2442 2443
    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) {
2444
        addReplyError(c,"min or max is not a float");
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
        return;
    }

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

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

        /* Use the first element in range as the starting point */
2458
        eptr = zzlFirstInRange(zl,&range);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468

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

        /* First element is in range */
        sptr = ziplistNext(zl,eptr);
        score = zzlGetScore(sptr);
2469
        redisAssertWithInfo(c,zobj,zslValueLteMax(score,&range));
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489

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

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

        /* Find first element in range */
2490
        zn = zslFirstInRange(zsl, &range);
2491 2492 2493 2494 2495 2496 2497

        /* 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 */
2498
            zn = zslLastInRange(zsl, &range);
2499 2500 2501 2502 2503 2504 2505 2506 2507

            /* 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 已提交
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526
    }

    addReplyLongLong(c, count);
}

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

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

    /* Lookup the sorted set */
    if ((zobj = lookupKeyReadOrReply(c, key, shared.czero)) == NULL ||
2527 2528 2529 2530 2531
        checkType(c, zobj, REDIS_ZSET))
    {
        zslFreeLexRange(&range);
        return;
    }
A
antirez 已提交
2532 2533 2534 2535 2536 2537

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

        /* Use the first element in range as the starting point */
2538
        eptr = zzlFirstInLexRange(zl,&range);
A
antirez 已提交
2539 2540 2541

        /* No "first" element */
        if (eptr == NULL) {
2542
            zslFreeLexRange(&range);
A
antirez 已提交
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
            addReply(c, shared.czero);
            return;
        }

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

        /* Iterate over elements in range */
        while (eptr) {
            /* Abort when the node is no longer in range. */
            if (!zzlLexValueLteMax(eptr,&range)) {
                break;
            } else {
                count++;
                zzlNext(zl,&eptr,&sptr);
            }
        }
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *zn;
        unsigned long rank;

        /* Find first element in range */
2568
        zn = zslFirstInLexRange(zsl, &range);
A
antirez 已提交
2569 2570 2571 2572 2573 2574 2575

        /* 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 */
2576
            zn = zslLastInLexRange(zsl, &range);
A
antirez 已提交
2577 2578 2579 2580 2581 2582 2583 2584 2585

            /* 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");
2586 2587
    }

2588
    zslFreeLexRange(&range);
2589
    addReplyLongLong(c, count);
2590 2591
}

2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
/* This command implements ZRANGEBYLEX, ZREVRANGEBYLEX. */
void genericZrangebylexCommand(redisClient *c, int reverse) {
    zlexrangespec range;
    robj *key = c->argv[1];
    robj *zobj;
    long offset = 0, limit = -1;
    unsigned long rangelen = 0;
    void *replylen = NULL;
    int minidx, maxidx;

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

    if (zslParseLexRange(c->argv[minidx],c->argv[maxidx],&range) != REDIS_OK) {
        addReplyError(c,"min or max not valid string range item");
        return;
    }

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

        while (remaining) {
            if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
                if ((getLongFromObjectOrReply(c, c->argv[pos+1], &offset, NULL) != REDIS_OK) ||
                    (getLongFromObjectOrReply(c, c->argv[pos+2], &limit, NULL) != REDIS_OK)) return;
                pos += 3; remaining -= 3;
            } else {
2628
                zslFreeLexRange(&range);
2629 2630 2631 2632 2633 2634 2635 2636
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* Ok, lookup the key and get the range */
    if ((zobj = lookupKeyReadOrReply(c,key,shared.emptymultibulk)) == NULL ||
2637 2638 2639 2640 2641
        checkType(c,zobj,REDIS_ZSET))
    {
        zslFreeLexRange(&range);
        return;
    }
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651

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

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2652
            eptr = zzlLastInLexRange(zl,&range);
2653
        } else {
2654
            eptr = zzlFirstInLexRange(zl,&range);
2655 2656 2657 2658 2659
        }

        /* No "first" element in the specified interval. */
        if (eptr == NULL) {
            addReply(c, shared.emptymultibulk);
2660
            zslFreeLexRange(&range);
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
            return;
        }

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

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

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

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

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

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

            /* Move to next node */
            if (reverse) {
                zzlPrev(zl,&eptr,&sptr);
            } else {
                zzlNext(zl,&eptr,&sptr);
            }
        }
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        zskiplistNode *ln;

        /* If reversed, get the last node in range as starting point. */
        if (reverse) {
2716
            ln = zslLastInLexRange(zsl,&range);
2717
        } else {
2718
            ln = zslFirstInLexRange(zsl,&range);
2719 2720 2721 2722 2723
        }

        /* No "first" element in the specified interval. */
        if (ln == NULL) {
            addReply(c, shared.emptymultibulk);
2724
            zslFreeLexRange(&range);
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 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
            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");
    }

2765
    zslFreeLexRange(&range);
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
    setDeferredMultiBulkLength(c, replylen, rangelen);
}

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

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

2777
void zcardCommand(redisClient *c) {
2778 2779
    robj *key = c->argv[1];
    robj *zobj;
2780

2781 2782
    if ((zobj = lookupKeyReadOrReply(c,key,shared.czero)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2783

2784
    addReplyLongLong(c,zsetLength(zobj));
2785 2786 2787
}

void zscoreCommand(redisClient *c) {
2788 2789 2790
    robj *key = c->argv[1];
    robj *zobj;
    double score;
2791

2792 2793
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2794

2795
    if (zobj->encoding == REDIS_ENCODING_ZIPLIST) {
2796
        if (zzlFind(zobj->ptr,c->argv[2],&score) != NULL)
2797 2798 2799
            addReplyDouble(c,score);
        else
            addReply(c,shared.nullbulk);
2800
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2801 2802
        zset *zs = zobj->ptr;
        dictEntry *de;
2803

2804 2805 2806
        c->argv[2] = tryObjectEncoding(c->argv[2]);
        de = dictFind(zs->dict,c->argv[2]);
        if (de != NULL) {
2807
            score = *(double*)dictGetVal(de);
2808 2809 2810 2811 2812 2813
            addReplyDouble(c,score);
        } else {
            addReply(c,shared.nullbulk);
        }
    } else {
        redisPanic("Unknown sorted set encoding");
2814 2815 2816 2817
    }
}

void zrankGenericCommand(redisClient *c, int reverse) {
2818 2819 2820 2821
    robj *key = c->argv[1];
    robj *ele = c->argv[2];
    robj *zobj;
    unsigned long llen;
2822 2823
    unsigned long rank;

2824 2825
    if ((zobj = lookupKeyReadOrReply(c,key,shared.nullbulk)) == NULL ||
        checkType(c,zobj,REDIS_ZSET)) return;
2826
    llen = zsetLength(zobj);
2827

2828 2829
    redisAssertWithInfo(c,ele,sdsEncodedObject(ele));

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

2834
        eptr = ziplistIndex(zl,0);
2835
        redisAssertWithInfo(c,zobj,eptr != NULL);
2836
        sptr = ziplistNext(zl,eptr);
2837
        redisAssertWithInfo(c,zobj,sptr != NULL);
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

        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);
2852
        } else {
2853 2854
            addReply(c,shared.nullbulk);
        }
2855
    } else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
2856 2857 2858 2859 2860 2861 2862 2863
        zset *zs = zobj->ptr;
        zskiplist *zsl = zs->zsl;
        dictEntry *de;
        double score;

        ele = c->argv[2] = tryObjectEncoding(c->argv[2]);
        de = dictFind(zs->dict,ele);
        if (de != NULL) {
2864
            score = *(double*)dictGetVal(de);
2865
            rank = zslGetRank(zsl,score,ele);
2866
            redisAssertWithInfo(c,ele,rank); /* Existing elements always have a rank. */
2867 2868 2869 2870 2871 2872
            if (reverse)
                addReplyLongLong(c,llen-rank);
            else
                addReplyLongLong(c,rank-1);
        } else {
            addReply(c,shared.nullbulk);
2873 2874
        }
    } else {
2875
        redisPanic("Unknown sorted set encoding");
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
    }
}

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

void zrevrankCommand(redisClient *c) {
    zrankGenericCommand(c, 1);
}
A
antirez 已提交
2886 2887 2888

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

2891
    if (parseScanCursorOrReply(c,c->argv[2],&cursor) == REDIS_ERR) return;
2892
    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptyscan)) == NULL ||
A
antirez 已提交
2893
        checkType(c,o,REDIS_ZSET)) return;
2894
    scanGenericCommand(c,o,cursor);
A
antirez 已提交
2895
}