package ledis import ( "bytes" "errors" "regexp" ) var errDataType = errors.New("error data type") var errMetaKey = errors.New("error meta key") func (db *DB) scan(dataType byte, key []byte, count int, inclusive bool, match string) ([][]byte, error) { var minKey, maxKey []byte var err error var r *regexp.Regexp if len(match) > 0 { if r, err = regexp.Compile(match); err != nil { return nil, err } } if len(key) > 0 { if err = checkKeySize(key); err != nil { return nil, err } if minKey, err = db.encodeScanKey(dataType, key); err != nil { return nil, err } } else { if minKey, err = db.encodeScanMinKey(dataType); err != nil { return nil, err } } if maxKey, err = db.encodeScanMaxKey(dataType); err != nil { return nil, err } if count <= 0 { count = defaultScanCount } v := make([][]byte, 0, count) it := db.bucket.NewIterator() it.Seek(minKey) if !inclusive { if it.Valid() && bytes.Equal(it.RawKey(), minKey) { it.Next() } } for i := 0; it.Valid() && i < count && bytes.Compare(it.RawKey(), maxKey) < 0; it.Next() { if k, err := db.decodeScanKey(dataType, it.Key()); err != nil { continue } else if r != nil && !r.Match(k) { continue } else { v = append(v, k) i++ } } it.Close() return v, nil } func (db *DB) encodeScanMinKey(dataType byte) ([]byte, error) { return db.encodeScanKey(dataType, nil) } func (db *DB) encodeScanMaxKey(dataType byte) ([]byte, error) { k, err := db.encodeScanKey(dataType, nil) if err != nil { return nil, err } k[len(k)-1] = dataType + 1 return k, nil } func (db *DB) encodeScanKey(dataType byte, key []byte) ([]byte, error) { switch dataType { case KVType: return db.encodeKVKey(key), nil case LMetaType: return db.lEncodeMetaKey(key), nil case HSizeType: return db.hEncodeSizeKey(key), nil case ZSizeType: return db.zEncodeSizeKey(key), nil case BitMetaType: return db.bEncodeMetaKey(key), nil case SSizeType: return db.sEncodeSizeKey(key), nil default: return nil, errDataType } } func (db *DB) decodeScanKey(dataType byte, ek []byte) ([]byte, error) { if len(ek) < 2 || ek[0] != db.index || ek[1] != dataType { return nil, errMetaKey } return ek[2:], nil }