// Copyright (c) 2011-2016 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include #include #include #include #include "JsonInputStreamSerializer.h" #include "JsonOutputStreamSerializer.h" #include "KVBinaryInputStreamSerializer.h" #include "KVBinaryOutputStreamSerializer.h" namespace Common { template T getValueAs(const JsonValue& js) { return js; //cdstatic_assert(false, "undefined conversion"); } template <> inline std::string getValueAs(const JsonValue& js) { return js.getString(); } template <> inline uint64_t getValueAs(const JsonValue& js) { return static_cast(js.getInteger()); } } namespace CryptoNote { template Common::JsonValue storeToJsonValue(const T& v) { JsonOutputStreamSerializer s; serialize(const_cast(v), s); return s.getValue(); } template Common::JsonValue storeContainerToJsonValue(const T& cont) { Common::JsonValue js(Common::JsonValue::ARRAY); for (const auto& item : cont) { js.pushBack(item); } return js; } template Common::JsonValue storeToJsonValue(const std::vector& v) { return storeContainerToJsonValue(v); } template Common::JsonValue storeToJsonValue(const std::list& v) { return storeContainerToJsonValue(v); } template <> inline Common::JsonValue storeToJsonValue(const std::string& v) { return Common::JsonValue(v); } template void loadFromJsonValue(T& v, const Common::JsonValue& js) { JsonInputValueSerializer s(js); serialize(v, s); } template void loadFromJsonValue(std::vector& v, const Common::JsonValue& js) { for (size_t i = 0; i < js.size(); ++i) { v.push_back(Common::getValueAs(js[i])); } } template void loadFromJsonValue(std::list& v, const Common::JsonValue& js) { for (size_t i = 0; i < js.size(); ++i) { v.push_back(Common::getValueAs(js[i])); } } template std::string storeToJson(const T& v) { return storeToJsonValue(v).toString(); } template bool loadFromJson(T& v, const std::string& buf) { try { if (buf.empty()) { return true; } auto js = Common::JsonValue::fromString(buf); loadFromJsonValue(v, js); } catch (std::exception&) { return false; } return true; } template std::string storeToBinaryKeyValue(const T& v) { KVBinaryOutputStreamSerializer s; serialize(const_cast(v), s); std::string result; Common::StringOutputStream stream(result); s.dump(stream); return result; } template bool loadFromBinaryKeyValue(T& v, const std::string& buf) { try { Common::MemoryInputStream stream(buf.data(), buf.size()); KVBinaryInputStreamSerializer s(stream); serialize(v, s); return true; } catch (std::exception&) { return false; } } }