diff --git a/database/leveldb.go b/database/leveldb.go index d112e3b8..dfbae96b 100644 --- a/database/leveldb.go +++ b/database/leveldb.go @@ -19,6 +19,7 @@ type Storage interface { Get(key []byte) ([]byte, error) Put(key []byte, value []byte) error Delete(key []byte) error + KeysByPrefix(prefix []byte) [][]byte FetchByPrefix(prefix []byte) [][]byte Close() error } @@ -65,6 +66,24 @@ func (l *levelDB) Delete(key []byte) error { return l.db.Delete(key, nil) } +func (l *levelDB) KeysByPrefix(prefix []byte) [][]byte { + result := make([][]byte, 0, 20) + iterator := l.db.NewIterator(nil) + if iterator.Seek(prefix) { + for bytes.HasPrefix(iterator.Key(), prefix) { + key := iterator.Key() + keyc := make([]byte, len(key)) + copy(keyc, key) + result = append(result, keyc) + if !iterator.Next() { + break + } + } + } + + return result +} + func (l *levelDB) FetchByPrefix(prefix []byte) [][]byte { result := make([][]byte, 0, 20) diff --git a/database/leveldb_test.go b/database/leveldb_test.go index 31e00370..bd4f95da 100644 --- a/database/leveldb_test.go +++ b/database/leveldb_test.go @@ -64,19 +64,23 @@ func (s *LevelDBSuite) TestDelete(c *C) { c.Assert(err, IsNil) } -func (s *LevelDBSuite) TestFetchByPrefix(c *C) { +func (s *LevelDBSuite) TestByPrefix(c *C) { c.Check(s.db.FetchByPrefix([]byte{0x80}), DeepEquals, [][]byte{}) s.db.Put([]byte{0x80, 0x01}, []byte{0x01}) s.db.Put([]byte{0x80, 0x03}, []byte{0x03}) s.db.Put([]byte{0x80, 0x02}, []byte{0x02}) c.Check(s.db.FetchByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x01}, {0x02}, {0x03}}) + c.Check(s.db.KeysByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x80, 0x01}, {0x80, 0x02}, {0x80, 0x03}}) s.db.Put([]byte{0x90, 0x01}, []byte{0x04}) c.Check(s.db.FetchByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x01}, {0x02}, {0x03}}) + c.Check(s.db.KeysByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x80, 0x01}, {0x80, 0x02}, {0x80, 0x03}}) s.db.Put([]byte{0x00, 0x01}, []byte{0x05}) c.Check(s.db.FetchByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x01}, {0x02}, {0x03}}) + c.Check(s.db.KeysByPrefix([]byte{0x80}), DeepEquals, [][]byte{{0x80, 0x01}, {0x80, 0x02}, {0x80, 0x03}}) c.Check(s.db.FetchByPrefix([]byte{0xa0}), DeepEquals, [][]byte{}) + c.Check(s.db.KeysByPrefix([]byte{0xa0}), DeepEquals, [][]byte{}) }