github.com/igggame/nebulas-go@v2.1.0+incompatible/nbre/fs/storage.h (about) 1 // Copyright (C) 2018 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 6 // modify 7 // it under the terms of the GNU General Public License as published by 8 // the Free Software Foundation, either version 3 of the License, or 9 // (at your option) any later version. 10 // 11 // the go-nebulas library is distributed in the hope that it will be useful, 12 // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 // GNU General Public License for more details. 15 // 16 // You should have received a copy of the GNU General Public License 17 // along with the go-nebulas library. If not, see 18 // <http://www.gnu.org/licenses/>. 19 // 20 #pragma once 21 #include "common/byte.h" 22 #include "common/common.h" 23 24 namespace neb { 25 namespace fs { 26 enum storage_open_flag { 27 storage_open_for_readwrite, 28 storage_open_for_readonly, 29 storage_open_default = storage_open_for_readonly, 30 }; 31 32 struct storage_general_failure : public std::exception { 33 inline storage_general_failure(const std::string &msg) : m_msg(msg) {} 34 inline const char *what() const throw() { return m_msg.c_str(); } 35 protected: 36 std::string m_msg; 37 }; 38 struct storage_exception_no_such_key : public std::exception { 39 inline const char *what() const throw() { return "no such key in storage"; } 40 }; 41 struct storage_exception_no_init : public std::exception { 42 inline const char *what() const throw() { return "storage no initialized"; } 43 }; 44 45 class storage { 46 public: 47 template <typename T, typename KT> 48 auto get(const KT &key) -> typename std::enable_if< 49 std::is_arithmetic<T>::value && std::is_arithmetic<KT>::value, T>::type { 50 return byte_to_number<T>(get_bytes(number_to_byte<bytes>(key))); 51 } 52 53 template <typename T, typename KT> 54 auto put(const KT &key, const T &val) -> 55 typename std::enable_if<std::is_arithmetic<T>::value && 56 std::is_arithmetic<KT>::value, 57 void>::type { 58 put_bytes(number_to_byte<bytes>(key), number_to_byte<bytes>(val)); 59 } 60 template <typename KT> 61 auto del(const KT &key) -> 62 typename std::enable_if<std::is_arithmetic<KT>::value, void>::type { 63 del_by_bytes(number_to_byte<bytes>(key)); 64 } 65 66 bytes get(const std::string &key) { return get_bytes(string_to_byte(key)); } 67 void put(const std::string &key, const bytes &value) { 68 return put_bytes(string_to_byte(key), value); 69 } 70 void del(const std::string &key) { del_by_bytes(string_to_byte(key)); } 71 72 virtual bytes get_bytes(const bytes &key) = 0; 73 virtual void put_bytes(const bytes &key, const bytes &val) = 0; 74 virtual void del_by_bytes(const bytes &key) = 0; 75 76 virtual void enable_batch() = 0; 77 virtual void disable_batch() = 0; 78 virtual void flush() = 0; 79 }; 80 } 81 }