memorydb.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 the entire keyspace
  113. // contained within the memory database.
  114. func (db *Database) NewIterator() ethdb.Iterator {
  115. return db.NewIteratorWithStart(nil)
  116. }
  117. // NewIteratorWithStart creates a binary-alphabetical iterator over a subset of
  118. // database content starting at a particular initial key (or after, if it does
  119. // not exist).
  120. func (db *Database) NewIteratorWithStart(start []byte) ethdb.Iterator {
  121. db.lock.RLock()
  122. defer db.lock.RUnlock()
  123. var (
  124. st = string(start)
  125. keys = make([]string, 0, len(db.db))
  126. values = make([][]byte, 0, len(db.db))
  127. )
  128. // Collect the keys from the memory database corresponding to the given start
  129. for key := range db.db {
  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. // NewIteratorWithPrefix creates a binary-alphabetical iterator over a subset
  145. // of database content with a particular key prefix.
  146. func (db *Database) NewIteratorWithPrefix(prefix []byte) ethdb.Iterator {
  147. db.lock.RLock()
  148. defer db.lock.RUnlock()
  149. var (
  150. pr = string(prefix)
  151. keys = make([]string, 0, len(db.db))
  152. values = make([][]byte, 0, len(db.db))
  153. )
  154. // Collect the keys from the memory database corresponding to the given prefix
  155. for key := range db.db {
  156. if strings.HasPrefix(key, pr) {
  157. keys = append(keys, key)
  158. }
  159. }
  160. // Sort the items and retrieve the associated values
  161. sort.Strings(keys)
  162. for _, key := range keys {
  163. values = append(values, db.db[key])
  164. }
  165. return &iterator{
  166. keys: keys,
  167. values: values,
  168. }
  169. }
  170. // Stat returns a particular internal stat of the database.
  171. func (db *Database) Stat(property string) (string, error) {
  172. return "", errors.New("unknown property")
  173. }
  174. // Compact is not supported on a memory database, but there's no need either as
  175. // a memory database doesn't waste space anyway.
  176. func (db *Database) Compact(start []byte, limit []byte) error {
  177. return nil
  178. }
  179. // Len returns the number of entries currently present in the memory database.
  180. //
  181. // Note, this method is only used for testing (i.e. not public in general) and
  182. // does not have explicit checks for closed-ness to allow simpler testing code.
  183. func (db *Database) Len() int {
  184. db.lock.RLock()
  185. defer db.lock.RUnlock()
  186. return len(db.db)
  187. }
  188. // keyvalue is a key-value tuple tagged with a deletion field to allow creating
  189. // memory-database write batches.
  190. type keyvalue struct {
  191. key []byte
  192. value []byte
  193. delete bool
  194. }
  195. // batch is a write-only memory batch that commits changes to its host
  196. // database when Write is called. A batch cannot be used concurrently.
  197. type batch struct {
  198. db *Database
  199. writes []keyvalue
  200. size int
  201. }
  202. // Put inserts the given value into the batch for later committing.
  203. func (b *batch) Put(key, value []byte) error {
  204. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), common.CopyBytes(value), false})
  205. b.size += len(value)
  206. return nil
  207. }
  208. // Delete inserts the a key removal into the batch for later committing.
  209. func (b *batch) Delete(key []byte) error {
  210. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), nil, true})
  211. b.size += 1
  212. return nil
  213. }
  214. // ValueSize retrieves the amount of data queued up for writing.
  215. func (b *batch) ValueSize() int {
  216. return b.size
  217. }
  218. // Write flushes any accumulated data to the memory database.
  219. func (b *batch) Write() error {
  220. b.db.lock.Lock()
  221. defer b.db.lock.Unlock()
  222. for _, keyvalue := range b.writes {
  223. if keyvalue.delete {
  224. delete(b.db.db, string(keyvalue.key))
  225. continue
  226. }
  227. b.db.db[string(keyvalue.key)] = keyvalue.value
  228. }
  229. return nil
  230. }
  231. // Reset resets the batch for reuse.
  232. func (b *batch) Reset() {
  233. b.writes = b.writes[:0]
  234. b.size = 0
  235. }
  236. // Replay replays the batch contents.
  237. func (b *batch) Replay(w ethdb.KeyValueWriter) error {
  238. for _, keyvalue := range b.writes {
  239. if keyvalue.delete {
  240. if err := w.Delete(keyvalue.key); err != nil {
  241. return err
  242. }
  243. continue
  244. }
  245. if err := w.Put(keyvalue.key, keyvalue.value); err != nil {
  246. return err
  247. }
  248. }
  249. return nil
  250. }
  251. // iterator can walk over the (potentially partial) keyspace of a memory key
  252. // value store. Internally it is a deep copy of the entire iterated state,
  253. // sorted by keys.
  254. type iterator struct {
  255. inited bool
  256. keys []string
  257. values [][]byte
  258. }
  259. // Next moves the iterator to the next key/value pair. It returns whether the
  260. // iterator is exhausted.
  261. func (it *iterator) Next() bool {
  262. // If the iterator was not yet initialized, do it now
  263. if !it.inited {
  264. it.inited = true
  265. return len(it.keys) > 0
  266. }
  267. // Iterator already initialize, advance it
  268. if len(it.keys) > 0 {
  269. it.keys = it.keys[1:]
  270. it.values = it.values[1:]
  271. }
  272. return len(it.keys) > 0
  273. }
  274. // Error returns any accumulated error. Exhausting all the key/value pairs
  275. // is not considered to be an error. A memory iterator cannot encounter errors.
  276. func (it *iterator) Error() error {
  277. return nil
  278. }
  279. // Key returns the key of the current key/value pair, or nil if done. The caller
  280. // should not modify the contents of the returned slice, and its contents may
  281. // change on the next call to Next.
  282. func (it *iterator) Key() []byte {
  283. if len(it.keys) > 0 {
  284. return []byte(it.keys[0])
  285. }
  286. return nil
  287. }
  288. // Value returns the value of the current key/value pair, or nil if done. The
  289. // caller should not modify the contents of the returned slice, and its contents
  290. // may change on the next call to Next.
  291. func (it *iterator) Value() []byte {
  292. if len(it.values) > 0 {
  293. return it.values[0]
  294. }
  295. return nil
  296. }
  297. // Release releases associated resources. Release should always succeed and can
  298. // be called multiple times without causing error.
  299. func (it *iterator) Release() {
  300. it.keys, it.values = nil, nil
  301. }