github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/signer/storage/storage.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser 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-aigar 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 Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package storage 19 20 import "errors" 21 22 var ( 23 // ErrZeroKey is returned if an attempt was made to inset a 0-length key. 24 ErrZeroKey = errors.New("0-length key") 25 26 // ErrNotFound is returned if an unknown key is attempted to be retrieved. 27 ErrNotFound = errors.New("not found") 28 ) 29 30 type Storage interface { 31 // Put stores a value by key. 0-length keys results in noop. 32 Put(key, value string) 33 34 // Get returns the previously stored value, or an error if the key is 0-length 35 // or unknown. 36 Get(key string) (string, error) 37 38 // Del removes a key-value pair. If the key doesn't exist, the method is a noop. 39 Del(key string) 40 } 41 42 // EphemeralStorage is an in-memory storage that does 43 // not persist values to disk. Mainly used for testing 44 type EphemeralStorage struct { 45 data map[string]string 46 namespace string 47 } 48 49 // Put stores a value by key. 0-length keys results in noop. 50 func (s *EphemeralStorage) Put(key, value string) { 51 if len(key) == 0 { 52 return 53 } 54 s.data[key] = value 55 } 56 57 // Get returns the previously stored value, or an error if the key is 0-length 58 // or unknown. 59 func (s *EphemeralStorage) Get(key string) (string, error) { 60 if len(key) == 0 { 61 return "", ErrZeroKey 62 } 63 if v, ok := s.data[key]; ok { 64 return v, nil 65 } 66 return "", ErrNotFound 67 } 68 69 // Del removes a key-value pair. If the key doesn't exist, the method is a noop. 70 func (s *EphemeralStorage) Del(key string) { 71 delete(s.data, key) 72 } 73 74 func NewEphemeralStorage() Storage { 75 s := &EphemeralStorage{ 76 data: make(map[string]string), 77 } 78 return s 79 } 80 81 // NoStorage is a dummy construct which doesn't remember anything you tell it 82 type NoStorage struct{} 83 84 func (s *NoStorage) Put(key, value string) {} 85 func (s *NoStorage) Del(key string) {} 86 func (s *NoStorage) Get(key string) (string, error) { 87 return "", errors.New("I forgot") 88 }