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