frostfs-node/pkg/local_object_storage/kvio/util.go
Alejandro Lopez 00c8712dc6 [#421] Create common interface for kv repositories
Signed-off-by: Alejandro Lopez <a.lopez@yadro.com>
2023-06-20 12:54:53 +03:00

70 lines
1.9 KiB
Go

package kvio
import "github.com/nspcc-dev/neo-go/pkg/util/slice"
// ForEachKey calls the given function for each key in the given repository in lexicographical order.
func ForEachKey(repo Repository, f func(Key) error) error {
return repo.Read(func(tx ReadOnlyTx) error {
cur := tx.IterateKeys()
defer cur.Close()
for ; cur.Key() != nil; cur.Next() {
if err := f(cur.Key()); err != nil {
return err
}
}
return nil
})
}
// ForEach calls the given function for each key-value entry in the given repository
// in lexicographical order of the keys.
func ForEach(repo Repository, f func(Key, Value) error) error {
return repo.Read(func(tx ReadOnlyTx) error {
cur := tx.Iterate()
defer cur.Close()
for ; cur.Key() != nil; cur.Next() {
var val Value
if err := cur.Value(func(v Value) error {
val = v
return nil
}); err != nil {
return err
}
if err := f(cur.Key(), val); err != nil {
return err
}
}
return nil
})
}
// Write writes a single key-value entry to the given repository.
// This is a convenience method that takes care of creating the appropriate transaction.
func Write(repo Repository, k Key, v Value) error {
return repo.Write(func(tx WriteOnlyTx) error {
return tx.Write(k, v)
})
}
// Read reads a single key-value entry from the given repository.
// This is a convenience method that takes care of creating the appropriate transaction.
func Read(repo Repository, k Key) (Value, error) {
var ret Value
err := repo.Read(func(tx ReadOnlyTx) error {
return tx.Read(k, func(v Value) error {
if v != nil {
ret = slice.Copy(v)
}
return nil
})
})
return ret, err
}
// Deletes deletes a single key-value entry from the given repository.
// This is a convenience method that takes care of creating the appropriate transaction.
func Delete(repo Repository, k Key) error {
return repo.Write(func(tx WriteOnlyTx) error {
return tx.Delete(k)
})
}