memorydb.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright 2014 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.
  175. func (db *Database) Compact(start []byte, limit []byte) error {
  176. return errors.New("unsupported operation")
  177. }
  178. // Len returns the number of entries currently present in the memory database.
  179. //
  180. // Note, this method is only used for testing (i.e. not public in general) and
  181. // does not have explicit checks for closed-ness to allow simpler testing code.
  182. func (db *Database) Len() int {
  183. db.lock.RLock()
  184. defer db.lock.RUnlock()
  185. return len(db.db)
  186. }
  187. // keyvalue is a key-value tuple tagged with a deletion field to allow creating
  188. // memory-database write batches.
  189. type keyvalue struct {
  190. key []byte
  191. value []byte
  192. delete bool
  193. }
  194. // batch is a write-only memory batch that commits changes to its host
  195. // database when Write is called. A batch cannot be used concurrently.
  196. type batch struct {
  197. db *Database
  198. writes []keyvalue
  199. size int
  200. }
  201. // Put inserts the given value into the batch for later committing.
  202. func (b *batch) Put(key, value []byte) error {
  203. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), common.CopyBytes(value), false})
  204. b.size += len(value)
  205. return nil
  206. }
  207. // Delete inserts the a key removal into the batch for later committing.
  208. func (b *batch) Delete(key []byte) error {
  209. b.writes = append(b.writes, keyvalue{common.CopyBytes(key), nil, true})
  210. b.size += 1
  211. return nil
  212. }
  213. // ValueSize retrieves the amount of data queued up for writing.
  214. func (b *batch) ValueSize() int {
  215. return b.size
  216. }
  217. // Write flushes any accumulated data to the memory database.
  218. func (b *batch) Write() error {
  219. b.db.lock.Lock()
  220. defer b.db.lock.Unlock()
  221. for _, keyvalue := range b.writes {
  222. if keyvalue.delete {
  223. delete(b.db.db, string(keyvalue.key))
  224. continue
  225. }
  226. b.db.db[string(keyvalue.key)] = keyvalue.value
  227. }
  228. return nil
  229. }
  230. // Reset resets the batch for reuse.
  231. func (b *batch) Reset() {
  232. b.writes = b.writes[:0]
  233. b.size = 0
  234. }
  235. // Replay replays the batch contents.
  236. func (b *batch) Replay(w ethdb.KeyValueWriter) error {
  237. for _, keyvalue := range b.writes {
  238. if keyvalue.delete {
  239. if err := w.Delete(keyvalue.key); err != nil {
  240. return err
  241. }
  242. continue
  243. }
  244. if err := w.Put(keyvalue.key, keyvalue.value); err != nil {
  245. return err
  246. }
  247. }
  248. return nil
  249. }
  250. // iterator can walk over the (potentially partial) keyspace of a memory key
  251. // value store. Internally it is a deep copy of the entire iterated state,
  252. // sorted by keys.
  253. type iterator struct {
  254. inited bool
  255. keys []string
  256. values [][]byte
  257. }
  258. // Next moves the iterator to the next key/value pair. It returns whether the
  259. // iterator is exhausted.
  260. func (it *iterator) Next() bool {
  261. // If the iterator was not yet initialized, do it now
  262. if !it.inited {
  263. it.inited = true
  264. return len(it.keys) > 0
  265. }
  266. // Iterator already initialize, advance it
  267. if len(it.keys) > 0 {
  268. it.keys = it.keys[1:]
  269. it.values = it.values[1:]
  270. }
  271. return len(it.keys) > 0
  272. }
  273. // Error returns any accumulated error. Exhausting all the key/value pairs
  274. // is not considered to be an error. A memory iterator cannot encounter errors.
  275. func (it *iterator) Error() error {
  276. return nil
  277. }
  278. // Key returns the key of the current key/value pair, or nil if done. The caller
  279. // should not modify the contents of the returned slice, and its contents may
  280. // change on the next call to Next.
  281. func (it *iterator) Key() []byte {
  282. if len(it.keys) > 0 {
  283. return []byte(it.keys[0])
  284. }
  285. return nil
  286. }
  287. // Value returns the value of the current key/value pair, or nil if done. The
  288. // caller should not modify the contents of the returned slice, and its contents
  289. // may change on the next call to Next.
  290. func (it *iterator) Value() []byte {
  291. if len(it.values) > 0 {
  292. return it.values[0]
  293. }
  294. return nil
  295. }
  296. // Release releases associated resources. Release should always succeed and can
  297. // be called multiple times without causing error.
  298. func (it *iterator) Release() {
  299. it.keys, it.values = nil, nil
  300. }