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.

76 lines
1.9 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 retreives the value for the given key
  27. // looking first in the content of the Tx, and
  28. // then into the content of the Storage
  29. Get([]byte) ([]byte, error)
  30. // Put sets the key & value into the Tx
  31. Put(k, v []byte) error
  32. // Add adds the given Tx into the Tx
  33. Add(Tx) error
  34. Commit() error
  35. Close()
  36. }
  37. // KV contains a key (K) and a value (V)
  38. type KV struct {
  39. K []byte
  40. V []byte
  41. }
  42. // KvMap is a key-value map between a sha256 byte array hash, and a KV struct
  43. type KvMap map[[sha256.Size]byte]KV
  44. // Get retreives the value respective to a key from the KvMap
  45. func (m KvMap) Get(k []byte) ([]byte, bool) {
  46. v, ok := m[sha256.Sum256(k)]
  47. return v.V, ok
  48. }
  49. // Put stores a key and a value in the KvMap
  50. func (m KvMap) Put(k, v []byte) {
  51. m[sha256.Sum256(k)] = KV{k, v}
  52. }
  53. // Concat concatenates arrays of bytes
  54. func Concat(vs ...[]byte) []byte {
  55. var b bytes.Buffer
  56. for _, v := range vs {
  57. b.Write(v)
  58. }
  59. return b.Bytes()
  60. }
  61. // Clone clones a byte array into a new byte array
  62. func Clone(b0 []byte) []byte {
  63. b1 := make([]byte, len(b0))
  64. copy(b1, b0)
  65. return b1
  66. }