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