Esempio n. 1
0
func (db *DB) zrank(key []byte, member []byte, reverse bool) (int64, error) {
	if err := checkZSetKMSize(key, member); err != nil {
		return 0, err
	}

	k := db.zEncodeSetKey(key, member)

	if v, err := db.db.Get(k); err != nil {
		return 0, err
	} else if v == nil {
		return -1, nil
	} else {
		if s, err := Int64(v, err); err != nil {
			return 0, err
		} else {
			var it *leveldb.Iterator

			sk := db.zEncodeScoreKey(key, member, s)

			if !reverse {
				minKey := db.zEncodeStartScoreKey(key, MinScore)
				it = db.db.Iterator(minKey, sk, leveldb.RangeClose, 0, -1)
			} else {
				maxKey := db.zEncodeStopScoreKey(key, MaxScore)
				it = db.db.RevIterator(sk, maxKey, leveldb.RangeClose, 0, -1)
			}

			var lastKey []byte = nil
			var n int64 = 0

			for ; it.Valid(); it.Next() {
				n++

				lastKey = it.Key()
			}

			it.Close()

			if _, m, _, err := db.zDecodeScoreKey(lastKey); err == nil && bytes.Equal(m, member) {
				n--
				return n, nil
			}
		}
	}

	return -1, nil
}
Esempio n. 2
0
func (db *DB) zRange(key []byte, min int64, max int64, withScores bool, offset int, limit int, reverse bool) ([]interface{}, error) {
	if len(key) > MaxKeySize {
		return nil, ErrKeySize
	}

	if offset < 0 {
		return []interface{}{}, nil
	}

	nv := 64
	if limit > 0 {
		nv = limit
	}
	if withScores {
		nv = 2 * nv
	}
	v := make([]interface{}, 0, nv)

	var it *leveldb.Iterator

	//if reverse and offset is 0, limit < 0, we may use forward iterator then reverse
	//because leveldb iterator prev is slower than next
	if !reverse || (offset == 0 && limit < 0) {
		it = db.zIterator(key, min, max, offset, limit, false)
	} else {
		it = db.zIterator(key, min, max, offset, limit, true)
	}

	for ; it.Valid(); it.Next() {
		_, m, s, err := db.zDecodeScoreKey(it.Key())
		//may be we will check key equal?
		if err != nil {
			continue
		}

		v = append(v, m)

		if withScores {
			v = append(v, StrPutInt64(s))
		}
	}

	if reverse && (offset == 0 && limit < 0) {
		v = db.zReverse(v, withScores)
	}

	return v, nil
}