You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.7 KiB

  1. package db
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "errors"
  6. )
  7. // ErrNotFound is used by the implementations of the interface db.Storage for
  8. // when a key is not found in the storage
  9. var ErrNotFound = errors.New("key not found")
  10. // Storage is the interface that defines the methods for the storage used in
  11. // the merkletree. Examples of the interface implementation can be found at
  12. // db/memory and db/leveldb directories.
  13. type Storage interface {
  14. NewTx() (Tx, error)
  15. WithPrefix(prefix []byte) Storage
  16. Get([]byte) ([]byte, error)
  17. List(int) ([]KV, error)
  18. Close()
  19. Info() string
  20. Iterate(func([]byte, []byte) (bool, error)) error
  21. }
  22. // Tx is the interface that defines the methods for the db transaction used in
  23. // the merkletree storage. Examples of the interface implementation can be
  24. // found at db/memory and db/leveldb directories.
  25. type Tx interface {
  26. Get([]byte) ([]byte, error)
  27. Put(k, v []byte)
  28. Add(Tx)
  29. Commit() error
  30. Close()
  31. }
  32. // KV contains a key (K) and a value (V)
  33. type KV struct {
  34. K []byte
  35. V []byte
  36. }
  37. // KvMap is a key-value map between a sha256 byte array hash, and a KV struct
  38. type KvMap map[[sha256.Size]byte]KV
  39. // Get retreives the value respective to a key from the KvMap
  40. func (m KvMap) Get(k []byte) ([]byte, bool) {
  41. v, ok := m[sha256.Sum256(k)]
  42. return v.V, ok
  43. }
  44. // Put stores a key and a value in the KvMap
  45. func (m KvMap) Put(k, v []byte) {
  46. m[sha256.Sum256(k)] = KV{k, v}
  47. }
  48. // Concat concatenates arrays of bytes
  49. func Concat(vs ...[]byte) []byte {
  50. var b bytes.Buffer
  51. for _, v := range vs {
  52. b.Write(v)
  53. }
  54. return b.Bytes()
  55. }
  56. // Clone clones a byte array into a new byte array
  57. func Clone(b0 []byte) []byte {
  58. b1 := make([]byte, len(b0))
  59. copy(b1, b0)
  60. return b1
  61. }