Given a sorted set object returns the 0-based rank of the object or * -1 if the object does not exist. * * For rank we mean the position of the element in the sorted collection * of elements. So the first element has rank 0, the second rank 1, and so * forth up to length-1 elements. * * If 'reverse' is false, the rank is returned considering as first element * the one with the lowest score
| 1517 | * the rank is computed considering as element with rank 0 the one with |
| 1518 | * the highest score. */ |
| 1519 | long zsetRank(robj_roptr zobj, sds ele, int reverse) { |
| 1520 | unsigned long llen; |
| 1521 | unsigned long rank; |
| 1522 | |
| 1523 | llen = zsetLength(zobj); |
| 1524 | |
| 1525 | if (zobj->encoding == OBJ_ENCODING_ZIPLIST) { |
| 1526 | unsigned char *zl = (unsigned char*)zobj->m_ptr; |
| 1527 | unsigned char *eptr, *sptr; |
| 1528 | |
| 1529 | eptr = ziplistIndex(zl,0); |
| 1530 | serverAssert(eptr != NULL); |
| 1531 | sptr = ziplistNext(zl,eptr); |
| 1532 | serverAssert(sptr != NULL); |
| 1533 | |
| 1534 | rank = 1; |
| 1535 | while(eptr != NULL) { |
| 1536 | if (ziplistCompare(eptr,(unsigned char*)ele,sdslen(ele))) |
| 1537 | break; |
| 1538 | rank++; |
| 1539 | zzlNext(zl,&eptr,&sptr); |
| 1540 | } |
| 1541 | |
| 1542 | if (eptr != NULL) { |
| 1543 | if (reverse) |
| 1544 | return llen-rank; |
| 1545 | else |
| 1546 | return rank-1; |
| 1547 | } else { |
| 1548 | return -1; |
| 1549 | } |
| 1550 | } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) { |
| 1551 | zset *zs = (zset*)zobj->m_ptr; |
| 1552 | zskiplist *zsl = zs->zsl; |
| 1553 | dictEntry *de; |
| 1554 | double score; |
| 1555 | |
| 1556 | de = dictFind(zs->dict,ele); |
| 1557 | if (de != NULL) { |
| 1558 | score = *(double*)dictGetVal(de); |
| 1559 | rank = zslGetRank(zsl,score,ele); |
| 1560 | /* Existing elements always have a rank. */ |
| 1561 | serverAssert(rank != 0); |
| 1562 | if (reverse) |
| 1563 | return llen-rank; |
| 1564 | else |
| 1565 | return rank-1; |
| 1566 | } else { |
| 1567 | return -1; |
| 1568 | } |
| 1569 | } else { |
| 1570 | serverPanic("Unknown sorted set encoding"); |
| 1571 | } |
| 1572 | } |
| 1573 | |
| 1574 | /* This is a helper function for the COPY command. |
| 1575 | * Duplicate a sorted set object, with the guarantee that the returned object |
no test coverage detected