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.

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