memorydb.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package memorydb implements the key-value database layer based on memory maps.
  17. package memorydb
  18. import (
  19. "errors"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/ethdb"
  25. )
  26. var (
  27. // errMemorydbClosed is returned if a memory database was already closed at the
  28. // invocation of a data access operation.
  29. errMemorydbClosed = errors.New("database closed")
  30. // errMemorydbNotFound is returned if a key is requested that is not found in
  31. // the provided memory database.
  32. errMemorydbNotFound = errors.New("not found")
  33. )
  34. // Database is an ephemeral key-value store. Apart from basic data storage
  35. // functionality it also supports batch writes and iterating over the keyspace in
  36. // binary-alphabetical order.
  37. type Database struct {
  38. db map[string][]byte
  39. lock sync.RWMutex
  40. }
  41. // New returns a wrapped map with all the required database interface methods
  42. // implemented.
  43. func New() *Database {
  44. return &Database{
  45. db: make(map[string][]byte),
  46. }
  47. }
  48. // NewWithCap returns a wrapped map pre-allocated to the provided capcity with
  49. // all the required database interface methods implemented.
  50. func NewWithCap(size int) *Database {
  51. return &Database{
  52. db: make(map[string][]byte, size),
  53. }
  54. }
  55. // Close deallocates the internal map and ensures any consecutive data access op
  56. // failes with an error.
  57. func (db *Database) Close() error {
  58. db.lock.Lock()
  59. defer db.lock.Unlock()
  60. db.db = nil
  61. return nil
  62. }
  63. // Has retrieves if a key is present in the key-value store.
  64. func (db *Database) Has(key []byte) (bool, error) {
  65. db.lock.RLock()
  66. defer db.lock.RUnlock()
  67. if db.db == nil {
  68. return false, errMemorydbClosed
  69. }
  70. _, ok := db.db[string(key)]
  71. return ok, nil
  72. }
  73. // Get retrieves the given key if it's present in the key-value store.
  74. func (db *Database) Get(key []byte) ([]byte, error) {
  75. db.lock.RLock()
  76. defer db.lock.RUnlock()
  77. if db.db == nil {
  78. return nil, errMemorydbClosed
  79. }
  80. if entry, ok := db.db[string(key)]; ok {
  81. return common.CopyBytes(entry), nil
  82. }
  83. return nil, errMemorydbNotFound
  84. }
  85. // Put inserts the given value into the key-value store.
  86. func (db *Database) Put(key []byte, value []byte) error {
  87. db.lock.Lock()
  88. defer db.lock.Unlock()
  89. if db.db == nil {
  90. return errMemorydbClosed
  91. }
  92. db.db[string(key)] = common.CopyBytes(value)
  93. return nil
  94. }
  95. // Delete removes the key from the key-value store.
  96. func (db *Database) Delete(key []byte) error {
  97. db.lock.Lock()
  98. defer db.lock.Unlock()
  99. if db.db == nil {
  100. return errMemorydbClosed
  101. }
  102. delete(db.db, string(key))
  103. return nil
  104. }
  105. // NewBatch creates a write-only key-value store that buffers changes to its host
  106. // database until a final write is called.
  107. func (db *Database) NewBatch() ethdb.Batch {
  108. return &batch{
  109. db: db,
  110. }
  111. }
  112. // NewIterator creates a binary-alphabetical iterator over a subset
  113. // of database content with a particular key prefix, starting at a particular
  114. // initial key (or after, if it does not exist).
  115. func (db *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator {
  116. db.lock.RLock()
  117. defer db.lock.RUnlock()
  118. var (
  119. pr = string(prefix)
  120. st = string(append(prefix, start...))
  121. keys = make([]string, 0, len(db.db))
  122. values = make([][]byte, 0, len(db.db))
  123. )
  124. // Collect the keys from the memory database corresponding to the given prefix
  125. // and start
  126. for key := range db.db {
  127. if !strings.HasPrefix(key, pr) {
  128. continue
  129. }
  130. if key >= st {
  131. keys = append(keys, key)
  132. }
  133. }
  134. // Sort the items and retrieve the associated values
  135. sort.Strings(keys)
  136. for _, key := range keys {
  137. values = append(values, db.db[key])
  138. }
  139. return &iterator{
  140. keys: keys,
  141. values: values,
  142. }
  143. }
  144. // Stat returns a particular internal stat of the database.
  145. func (db *Database) Stat(property string) (string, error) {
  146. return "", errors.New("unknown property")
  147. }
  148. // Compact is not supported on a memory database, but there's no need either as
  149. // a memory database doesn't waste space anyway.
  150. func (db *Database) Compact(start []byte, limit []byte) error {
  151. return nil
  152. }
  153. // Len returns the number of entries currently present in the memory database.
  154. //
  155. // Note, this method is only used for testing (i.e. not public in general) and
  156. // does not have explicit checks for closed-ness to allow simpler testing code.
  157. func (db *Database) Len() int {
  158. db.lock.RLock()
  159. defer db.lock.RUnlock()
  160. return len(db.db)
  161. }
  162. // keyvalue is a key-value tuple tagged with a deletion field to allow creating
  163. // memory-database write batches.
  164. type keyvalue struct {
  165. key []byte
  166. value []byte
  167. delete bool
  168. }
  169. // batch is a write-only memory batch that commits changes to its host
  170. // database when Write is called. A batch cannot be used concurrently.
  171. type batch struct {
  172. db *Database
  173. writes []keyvalue
  174. size int
  175. }
  176. // Put inserts the given value into the batch for later committing.
  177. func (b *batch) Put(key, value []byte) error {
  178. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), common.CopyBytes(value), false})
  179. b.size += len(value)
  180. return nil
  181. }
  182. // Delete inserts the a key removal into the batch for later committing.
  183. func (b *batch) Delete(key []byte) error {
  184. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), nil, true})
  185. b.size += len(key)
  186. return nil
  187. }
  188. // ValueSize retrieves the amount of data queued up for writing.
  189. func (b *batch) ValueSize() int {
  190. return b.size
  191. }
  192. // Write flushes any accumulated data to the memory database.
  193. func (b *batch) Write() error {
  194. b.db.lock.Lock()
  195. defer b.db.lock.Unlock()
  196. for _, keyvalue := range b.writes {
  197. if keyvalue.delete {
  198. delete(b.db.db, string(keyvalue.key))
  199. continue
  200. }
  201. b.db.db[string(keyvalue.key)] = keyvalue.value
  202. }
  203. return nil
  204. }
  205. // Reset resets the batch for reuse.
  206. func (b *batch) Reset() {
  207. b.writes = b.writes[:0]
  208. b.size = 0
  209. }
  210. // Replay replays the batch contents.
  211. func (b *batch) Replay(w ethdb.KeyValueWriter) error {
  212. for _, keyvalue := range b.writes {
  213. if keyvalue.delete {
  214. if err := w.Delete(keyvalue.key); err != nil {
  215. return err
  216. }
  217. continue
  218. }
  219. if err := w.Put(keyvalue.key, keyvalue.value); err != nil {
  220. return err
  221. }
  222. }
  223. return nil
  224. }
  225. // iterator can walk over the (potentially partial) keyspace of a memory key
  226. // value store. Internally it is a deep copy of the entire iterated state,
  227. // sorted by keys.
  228. type iterator struct {
  229. inited bool
  230. keys []string
  231. values [][]byte
  232. }
  233. // Next moves the iterator to the next key/value pair. It returns whether the
  234. // iterator is exhausted.
  235. func (it *iterator) Next() bool {
  236. // If the iterator was not yet initialized, do it now
  237. if !it.inited {
  238. it.inited = true
  239. return len(it.keys) > 0
  240. }
  241. // Iterator already initialize, advance it
  242. if len(it.keys) > 0 {
  243. it.keys = it.keys[1:]
  244. it.values = it.values[1:]
  245. }
  246. return len(it.keys) > 0
  247. }
  248. // Error returns any accumulated error. Exhausting all the key/value pairs
  249. // is not considered to be an error. A memory iterator cannot encounter errors.
  250. func (it *iterator) Error() error {
  251. return nil
  252. }
  253. // Key returns the key of the current key/value pair, or nil if done. The caller
  254. // should not modify the contents of the returned slice, and its contents may
  255. // change on the next call to Next.
  256. func (it *iterator) Key() []byte {
  257. if len(it.keys) > 0 {
  258. return []byte(it.keys[0])
  259. }
  260. return nil
  261. }
  262. // Value returns the value of the current key/value pair, or nil if done. The
  263. // caller should not modify the contents of the returned slice, and its contents
  264. // may change on the next call to Next.
  265. func (it *iterator) Value() []byte {
  266. if len(it.values) > 0 {
  267. return it.values[0]
  268. }
  269. return nil
  270. }
  271. // Release releases associated resources. Release should always succeed and can
  272. // be called multiple times without causing error.
  273. func (it *iterator) Release() {
  274. it.keys, it.values = nil, nil
  275. }