github.com/igggame/nebulas-go@v2.1.0+incompatible/storage/memory_storage.go (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 19 package storage 20 21 import ( 22 "sync" 23 24 "github.com/nebulasio/go-nebulas/util/byteutils" 25 ) 26 27 // MemoryStorage the nodes in trie. 28 type MemoryStorage struct { 29 data *sync.Map 30 } 31 32 // kv entry 33 type kv struct{ k, v []byte } 34 35 // MemoryBatch do batch task in memory storage 36 type MemoryBatch struct { 37 db *MemoryStorage 38 entries []*kv 39 } 40 41 // NewMemoryStorage init a storage 42 func NewMemoryStorage() (*MemoryStorage, error) { 43 return &MemoryStorage{ 44 data: new(sync.Map), 45 }, nil 46 } 47 48 // Get return value to the key in Storage 49 func (db *MemoryStorage) Get(key []byte) ([]byte, error) { 50 if entry, ok := db.data.Load(byteutils.Hex(key)); ok { 51 return entry.([]byte), nil 52 } 53 return nil, ErrKeyNotFound 54 } 55 56 // Put put the key-value entry to Storage 57 func (db *MemoryStorage) Put(key []byte, value []byte) error { 58 db.data.Store(byteutils.Hex(key), value) 59 return nil 60 } 61 62 // Del delete the key in Storage. 63 func (db *MemoryStorage) Del(key []byte) error { 64 db.data.Delete(byteutils.Hex(key)) 65 return nil 66 } 67 68 // EnableBatch enable batch write. 69 func (db *MemoryStorage) EnableBatch() { 70 } 71 72 // Flush write and flush pending batch write. 73 func (db *MemoryStorage) Flush() error { 74 return nil 75 } 76 77 // DisableBatch disable batch write. 78 func (db *MemoryStorage) DisableBatch() { 79 }