From 56b330648366cf7c22f8858a091afe96e7abc9c7 Mon Sep 17 00:00:00 2001 From: PhilipDeegan Date: Thu, 19 Nov 2026 12:47:24 +0100 Subject: [PATCH 1/2] cbor --- include/cppconfig/cppconfig.hpp | 2 +- include/cppconfig/io/cbor.hpp | 566 ++++++++++++++++++++++++++++++++ meson.build | 8 +- tests/cbor/test.cpp | 319 ++++++++++++++++++ 4 files changed, 890 insertions(+), 5 deletions(-) create mode 100644 include/cppconfig/io/cbor.hpp create mode 100644 tests/cbor/test.cpp diff --git a/include/cppconfig/cppconfig.hpp b/include/cppconfig/cppconfig.hpp index e0a9c5d..c6b4c73 100644 --- a/include/cppconfig/cppconfig.hpp +++ b/include/cppconfig/cppconfig.hpp @@ -24,7 +24,7 @@ #include "io/yaml.hpp" #include #include -#include + namespace cppconfig { diff --git a/include/cppconfig/io/cbor.hpp b/include/cppconfig/io/cbor.hpp new file mode 100644 index 0000000..629045a --- /dev/null +++ b/include/cppconfig/io/cbor.hpp @@ -0,0 +1,566 @@ +/*------------------------------------------------------------------------------ +-- This file is a part of the C++ Config library +-- Copyright (C) 2022, Plasma Physics Laboratory - CNRS +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; either version 2 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +-------------------------------------------------------------------------------*/ +/*-- Author : Alexis Jeandet +-- Mail : alexis.jeandet@lpp.polytechnique.fr +----------------------------------------------------------------------------*/ +#pragma once + +/* + CBOR (RFC 8949) file layout, portable across endianness and ABIs: + + file := { "format": "cppconfig", "version": 1, "root": map | null } + node := map | leaf + map := { key: node, ... } + leaf := [ type_name, value ] + + value(bool) := bool + value(integral) := integer range checked on load + value(floating point) := float + value(range of char) := text string e.g. std::string + value(range of arithmetic) := [ value, ... ] e.g. std::vector, std::array + value(custom serializable) := map the Dict produced by serialize(Dict&, T + const&) + + type_name is derived from the type itself, not from its position in Dict, so reordering + or adding leaf types does not invalidate existing files: + "bool", "i8".."i64", "u8".."u64", "f32", "f64", "str", "str[N]", "vec", "arr" + Custom types are named "obj" unless an ADL-findable + cppconfig_type_name(std::type_identity) -> string + is provided. Names must be unique within a Dict, so a Dict holding more than one custom type + must name them. Prefer fixed width integers (std::int64_t, ...) as leaf types: `long` is "i64" + on Linux but "i32" on Windows. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "dict.hpp" + +namespace cppconfig::config_cbor +{ +using json = nlohmann::json; + +inline constexpr int format_version = 1; + + +template +std::vector to_bytes(Config const& config); + +template +Config from_bytes(std::vector const& bytes); + +template +void save_config(std::filesystem::path const& file, Config const& config); + +template +Config load_config(std::filesystem::path const& file); + + +template +concept HasSerialize = requires(Dict& dict, T const& data) { serialize(dict, data); }; + +template +concept HasDeserialize = requires(Dict const& dict, T& data) { deserialize(dict, data); }; + +template +concept IsCustomSerializable = HasSerialize and HasDeserialize; + +} // namespace cppconfig::config_cbor + + +namespace cppconfig::config_cbor::detail +{ +template +concept HasTypeName = requires { + { cppconfig_type_name(std::type_identity {}) } -> std::convertible_to; +}; + +template +concept CharLike = std::same_as or std::same_as or std::same_as + or std::same_as or std::same_as; + +// arithmetic types with a platform independent meaning +template +concept PortableArithmetic + = std::same_as or (std::integral and !CharLike and sizeof(T) <= 8) + or (std::floating_point and std::numeric_limits::is_iec559 + and (sizeof(T) == 4 or sizeof(T) == 8)); + +// owning sized range, e.g. std::vector, std::array, std::string +template +concept Sequence = std::ranges::forward_range and std::ranges::sized_range + and !std::ranges::view and std::default_initializable; + +template +concept Resizable = Sequence and requires(T& t, std::size_t n) { t.resize(n); }; + +template +concept Text = Sequence and std::same_as, char>; + +template +concept NumericSequence + = Sequence and !Text and PortableArithmetic>; +} // namespace cppconfig::config_cbor::detail + + +namespace cppconfig::config_cbor +{ +template +concept CborSerializable = IsCustomSerializable or detail::PortableArithmetic + or detail::Text or detail::NumericSequence; +} // namespace cppconfig::config_cbor + + +namespace cppconfig::config_cbor::detail +{ +[[noreturn]] inline void fail(std::string const& what, std::string const& path); + +template +std::string type_name(); + +template +std::string custom_type_name(); + +template +std::string sequence_type_name(); + +template +std::string extent_of(); + +// everything that needs the Ts... pack of a Dict +template +struct LeafTypes; + +template +struct LeafTypes> +{ + using Dict = cppdict::Dict; + + static_assert(((HasSerialize == HasDeserialize) and ...), + "cppconfig: a leaf type has only one of serialize()/deserialize() - both are required"); + static_assert((CborSerializable and ...), + "cppconfig: every leaf type must be bool, a fixed size integer, an IEEE float/double, " + "a range of char, a range of those arithmetic types, or custom-serializable via " + "serialize(Dict&, T const&) and deserialize(Dict const&, T&)"); + + static void check_unique_names(); + + // calls f.template operator()() for the leaf type T named `name`, false if none matches + template + static bool dispatch(std::string const& name, F&& f); +}; + + +template +struct Codec +{ + using node_t = typename Dict::node_t; + using empty_leaf_t = typename Dict::empty_leaf_t; + + static json encode_node(Dict const& node, std::string const& path); + static void decode_node(json const& j, Dict& node, std::string const& path); + +private: + static json encode_alternative(empty_leaf_t const&, std::string const& path); + static json encode_alternative(node_t const& map, std::string const& path); + template + static json encode_alternative(T const& leaf, std::string const& path); + + template + static json encode_value(T const& value, std::string const& path); + template + static json encode_custom(T const& value, std::string const& path); + template + static json encode_sequence(T const& value, std::string const& path); + + static void decode_leaf( + std::string const& name, json const& value, Dict& node, std::string const& path); + + template + static T decode_value(json const& j, std::string const& path); + template + static T decode_custom(json const& j, std::string const& path); + template + static T decode_text(json const& j, std::string const& path); + template + static T decode_sequence(json const& j, std::string const& path); + template + static T decode_integral(json const& j, std::string const& path); + template + static T decode_floating(json const& j, std::string const& path); + + template + static T sized(std::size_t n, std::string const& path); +}; + + +// ---------------------------------------------------------------- helpers + +[[noreturn]] inline void fail(std::string const& what, std::string const& path) +{ + throw std::runtime_error("cppconfig: " + what + " at '" + path + "'"); +} + +template +std::string extent_of() +{ + return std::to_string(std::ranges::size(T {})); +} + +template +std::string custom_type_name() +{ + if constexpr (HasTypeName) + return std::string { cppconfig_type_name(std::type_identity {}) }; + return "obj"; +} + +template +std::string sequence_type_name() +{ + auto const element = type_name>(); + if constexpr (Resizable) + return "vec<" + element + ">"; + return "arr<" + element + "," + extent_of() + ">"; +} + +template +std::string type_name() +{ + if constexpr (IsCustomSerializable) + return custom_type_name(); + else if constexpr (std::same_as) + return "bool"; + else if constexpr (std::integral) + return (std::is_signed_v ? "i" : "u") + std::to_string(8 * sizeof(T)); + else if constexpr (std::floating_point) + return "f" + std::to_string(8 * sizeof(T)); + else if constexpr (Text and Resizable) + return "str"; + else if constexpr (Text) + return "str[" + extent_of() + "]"; + else + return sequence_type_name(); +} + + +template +void LeafTypes>::check_unique_names() +{ + static auto const duplicate = []() -> std::string + { + std::vector names { type_name()... }; + std::ranges::sort(names); + auto const it = std::ranges::adjacent_find(names); + return it == names.end() ? "" : *it; + }(); + + if (!duplicate.empty()) + throw std::logic_error("cppconfig: duplicate leaf type name '" + duplicate + + "', provide cppconfig_type_name(std::type_identity) for custom types or use " + "distinct fixed width types"); +} + +template +template +bool LeafTypes>::dispatch(std::string const& name, F&& f) +{ + return ((name == type_name() ? (f.template operator()(), true) : false) or ...); +} + + +// ---------------------------------------------------------------- encode + +template +json Codec::encode_node(Dict const& node, std::string const& path) +{ + return std::visit( + [&](auto const& value) { return encode_alternative(value, path); }, node.data); +} + +template +json Codec::encode_alternative(empty_leaf_t const&, std::string const& path) +{ + fail("cannot serialize empty leaf", path); +} + +template +json Codec::encode_alternative(node_t const& map, std::string const& path) +{ + json obj = json::object(); + for (auto const& [key, child] : map) + obj[key] = encode_node(*child, path + "/" + key); + return obj; +} + +template +template +json Codec::encode_alternative(T const& leaf, std::string const& path) +{ + return json::array({ type_name(), encode_value(leaf, path) }); +} + +template +template +json Codec::encode_value(T const& value, std::string const& path) +{ + if constexpr (IsCustomSerializable) + return encode_custom(value, path); + else if constexpr (Text) + return std::string(std::ranges::begin(value), std::ranges::end(value)); + else if constexpr (NumericSequence) + return encode_sequence(value, path); + else + return json(value); +} + +template +template +json Codec::encode_custom(T const& value, std::string const& path) +{ + Dict temp; + serialize(temp, value); + if (temp.isEmpty()) + return json::object(); + if (!temp.isNode()) + fail("serialize() for a custom type must produce a map", path); + return encode_node(temp, path); +} + +template +template +json Codec::encode_sequence(T const& value, std::string const& path) +{ + json arr = json::array(); + for (auto const& e : value) + arr.push_back(encode_value>(e, path)); + return arr; +} + + +// ---------------------------------------------------------------- decode + +template +void Codec::decode_node(json const& j, Dict& node, std::string const& path) +{ + if (j.is_array() and j.size() == 2 and j[0].is_string()) + return decode_leaf(j[0].get_ref(), j[1], node, path); + + if (!j.is_object()) + fail("expected a map or a [type, value] leaf", path); + + node.data = node_t {}; // keep empty maps as maps + for (auto const& [key, value] : j.items()) + decode_node(value, node[key], path + "/" + key); +} + +template +void Codec::decode_leaf( + std::string const& name, json const& value, Dict& node, std::string const& path) +{ + auto const decode = [&]() { node = decode_value(value, path); }; + if (!LeafTypes::dispatch(name, decode)) + fail("unknown leaf type '" + name + "'", path); +} + +template +template +T Codec::decode_value(json const& j, std::string const& path) +{ + if constexpr (IsCustomSerializable) + return decode_custom(j, path); + else if constexpr (Text) + return decode_text(j, path); + else if constexpr (NumericSequence) + return decode_sequence(j, path); + else if constexpr (std::same_as) + return j.is_boolean() ? j.get() : (fail("expected a bool", path), false); + else if constexpr (std::integral) + return decode_integral(j, path); + else + return decode_floating(j, path); +} + +template +template +T Codec::decode_custom(json const& j, std::string const& path) +{ + if (!j.is_object()) + fail("expected a map for custom type '" + type_name() + "'", path); + Dict loader; + decode_node(j, loader, path); + T t; + deserialize(loader, t); + return t; +} + +template +template +T Codec::decode_text(json const& j, std::string const& path) +{ + if (!j.is_string()) + fail("expected a string", path); + auto const& s = j.get_ref(); + auto t = sized(s.size(), path); + std::ranges::copy(s, std::ranges::begin(t)); + return t; +} + +template +template +T Codec::decode_sequence(json const& j, std::string const& path) +{ + if (!j.is_array()) + fail("expected an array", path); + auto t = sized(j.size(), path); + auto it = std::ranges::begin(t); + for (auto const& e : j) + *it++ = decode_value>(e, path); + return t; +} + +template +template +T Codec::decode_integral(json const& j, std::string const& path) +{ + auto const narrow = [&](auto const v) + { + if (!std::in_range(v)) + fail( + "integer " + std::to_string(v) + " out of range for " + type_name(), path); + return static_cast(v); + }; + + if (j.is_number_unsigned()) + return narrow(j.get()); + if (j.is_number_integer()) + return narrow(j.get()); + fail("expected an integer", path); +} + +template +template +T Codec::decode_floating(json const& j, std::string const& path) +{ + if (!j.is_number_float()) + fail("expected a float", path); + auto const v = j.get(); + if (std::isfinite(v) and std::abs(v) > std::numeric_limits::max()) + fail("float " + std::to_string(v) + " out of range for " + type_name(), path); + return static_cast(v); +} + +template +template +T Codec::sized(std::size_t const n, std::string const& path) +{ + T t {}; + if constexpr (Resizable) + t.resize(n); + else if (std::ranges::size(t) != n) + fail("fixed size container length mismatch, file has " + std::to_string(n) + " expected " + + std::to_string(std::ranges::size(t)), + path); + return t; +} + + +} // namespace cppconfig::config_cbor::detail + + +namespace cppconfig::config_cbor +{ + + +// ---------------------------------------------------------------- public API + +template +std::vector to_bytes(Config const& config) +{ + detail::LeafTypes::check_unique_names(); + if (!config.isNode() and !config.isEmpty()) + throw std::runtime_error("cppconfig: root of a config must be a map"); + + auto const root = config.isNode() ? detail::Codec::encode_node(config, "") : json {}; + return json::to_cbor( + json { { "format", "cppconfig" }, { "version", format_version }, { "root", root } }); +} + +template +Config from_bytes(std::vector const& bytes) +{ + detail::LeafTypes::check_unique_names(); + + auto const doc = json::from_cbor(bytes); + if (!doc.is_object() or doc.value("format", "") != "cppconfig") + throw std::runtime_error("cppconfig: not a cppconfig CBOR document"); + if (!doc.contains("version") or doc["version"] != format_version) + throw std::runtime_error("cppconfig: unsupported cppconfig CBOR format version"); + + auto const& root = doc.value("root", json {}); + if (!root.is_object() and !root.is_null()) + throw std::runtime_error("cppconfig: root of a config must be a map"); + + Config config; + if (root.is_object()) + detail::Codec::decode_node(root, config, ""); + return config; +} + +template +void save_config(std::filesystem::path const& file, Config const& config) +{ + auto const bytes = to_bytes(config); + std::ofstream out { file, std::ios::binary }; + if (!out) + throw std::runtime_error("cppconfig: cannot open file for writing: " + file.string()); + out.write( + reinterpret_cast(bytes.data()), static_cast(bytes.size())); + if (!out.flush()) + throw std::runtime_error("cppconfig: write failed: " + file.string()); +} + +template +Config load_config(std::filesystem::path const& file) +{ + std::ifstream in { file, std::ios::binary }; + if (!in) + throw std::runtime_error("cppconfig: cannot open file for reading: " + file.string()); + std::vector const bytes { std::istreambuf_iterator { in }, {} }; + if (in.bad()) + throw std::runtime_error("cppconfig: read failed: " + file.string()); + return from_bytes(bytes); +} + +} // namespace cppconfig::config_cbor diff --git a/meson.build b/meson.build index 8c590ae..ffb91b4 100644 --- a/meson.build +++ b/meson.build @@ -1,8 +1,8 @@ project( 'cppconfig', 'cpp', - version : '1.0.0', - default_options : ['warning_level=3', 'cpp_std=c++17'], + version : '1.0.1', + default_options : ['warning_level=3', 'cpp_std=c++20', 'catch2:tests=false'], license : 'GPL3' ) @@ -16,9 +16,9 @@ cppconfig_dep = declare_dependency( dependencies:[yaml_cpp_dep, nlohmann_json_dep, cppdict_dep] ) -library('cppconfig', extra_files:['include/cppconfig/cppconfig.hpp', 'include/cppconfig/io/yaml.hpp', 'include/cppconfig/io/json.hpp']) +library('cppconfig', extra_files:['include/cppconfig/cppconfig.hpp', 'include/cppconfig/io/yaml.hpp', 'include/cppconfig/io/json.hpp', 'include/cppconfig/io/cbor.hpp']) -foreach test:['yaml','json'] +foreach test:['cbor', 'yaml', 'json'] exe = executable(test,'tests/'+test+'/test.cpp', dependencies:[cppconfig_dep, catch_dep], cpp_args : '-DCATCH_CONFIG_NO_POSIX_SIGNALS', diff --git a/tests/cbor/test.cpp b/tests/cbor/test.cpp new file mode 100644 index 0000000..370249f --- /dev/null +++ b/tests/cbor/test.cpp @@ -0,0 +1,319 @@ + + + +#include + +#include "cppconfig/io/cbor.hpp" + +#include +#include +#include +#include +#include +#include + +using namespace cppconfig::config_cbor; + + +TEST_CASE("can read/write", "[cppconfig]") +{ + using MyDict = cppdict::Dict>; + + std::string const file("outfile.cbor"); + + { + MyDict md; + md["PI"] = 3.14; + md["test"]["super"] = 2; + md["Key"] = std::string { "Value" }; + md["key2"] = 2; + md["vec"] = std::vector { 1, 2, 3 }; + + save_config(file, md); + } + + auto const md = load_config(file); + + REQUIRE(md["Key"].to() == "Value"); + REQUIRE(md["key2"].to() == 2); + REQUIRE(md["PI"].to() == 3.14); + REQUIRE(md["test"]["super"].to() == 2); + REQUIRE(md["vec"].to>() == std::vector { 1, 2, 3 }); +} + + +TEST_CASE("file is plain CBOR", "[cppconfig]") +{ + using MyDict = cppdict::Dict>; + MyDict md; + md["a"]["b"] = 1; + md["s"] = std::string { "x" }; + md["v"] = std::vector { 1.5, -2 }; + + auto const doc = json::from_cbor(to_bytes(md)); + REQUIRE(doc["format"] == "cppconfig"); + REQUIRE(doc["version"] == format_version); + REQUIRE(doc["root"]["a"]["b"] == json::array({ "i32", 1 })); + REQUIRE(doc["root"]["s"] == json::array({ "str", "x" })); + REQUIRE(doc["root"]["v"] == json::array({ "vec", { 1.5, -2.0 } })); +} + + +TEST_CASE("leaf type order does not matter", "[cppconfig]") +{ + cppdict::Dict md; + md["i"] = std::int64_t { 1 } << 40; + md["d"] = 0.5; + md["s"] = std::string { "s" }; + + auto const loaded = from_bytes>(to_bytes(md)); + REQUIRE(loaded["i"].to() == std::int64_t { 1 } << 40); + REQUIRE(loaded["d"].to() == 0.5); + REQUIRE(loaded["s"].to() == "s"); +} + + +struct CustomSerializable +{ + int a = 111; + double b = 333; + + bool operator==(CustomSerializable const& cs) const { return a == cs.a and b == cs.b; } +}; + +template +void serialize(cppdict::Dict& dict, CustomSerializable const& cm) +{ + dict["cm.a"] = cm.a; + dict["cm.b"] = cm.b; +} + +template +void deserialize(cppdict::Dict const& dict, CustomSerializable& cm) +{ + cm.a = dict["cm.a"].template to(); + cm.b = dict["cm.b"].template to(); +} + + +TEST_CASE("can read/write custom serializable", "[cppconfig]") +{ + using MyDict = cppdict::Dict; + static_assert(IsCustomSerializable); + + CustomSerializable const cs {}; + + SECTION("custom type fields written by hand") + { + MyDict md; + md["key"] = std::string { "Value" }; + md["custom"]["data"]["cm.a"] = cs.a; + md["custom"]["data"]["cm.b"] = cs.b; + md["custom"]["other"] = 3.3; + md["key2"] = 2; + save_config("outfile.0.cbor", md); + + auto const loaded = load_config("outfile.0.cbor"); + REQUIRE(loaded["key"].to() == "Value"); + REQUIRE(loaded["custom"]["data"]["cm.a"].to() == cs.a); + REQUIRE(loaded["custom"]["data"]["cm.b"].to() == cs.b); + REQUIRE(loaded["custom"]["other"].to() == 3.3); + REQUIRE(loaded["key2"].to() == 2); + } + + SECTION("direct custom type") + { + MyDict md; + md["key"] = std::string { "Value" }; + md["custom"]["data"] = cs; + md["custom"]["other"] = 3.3; + md["key2"] = 2; + save_config("outfile.1.cbor", md); + + auto const loaded = load_config("outfile.1.cbor"); + REQUIRE(loaded["key"].to() == "Value"); + REQUIRE(loaded["custom"]["other"].to() == 3.3); + REQUIRE(loaded["custom"]["data"].to() == cs); + REQUIRE(loaded["key2"].to() == 2); + } +} + + +namespace nested +{ +struct Inner +{ + std::vector v { 1, 2 }; + bool operator==(Inner const&) const = default; +}; + +struct Outer +{ + Inner inner { { 3, 4, 5 } }; + std::string name = "outer"; + bool operator==(Outer const&) const = default; +}; + +inline std::string cppconfig_type_name(std::type_identity) +{ + return "Inner"; +} +inline std::string cppconfig_type_name(std::type_identity) +{ + return "Outer"; +} + +template +void serialize(cppdict::Dict& dict, Inner const& in) +{ + dict["v"] = in.v; +} +template +void deserialize(cppdict::Dict const& dict, Inner& in) +{ + in.v = dict["v"].template to>(); +} + +template +void serialize(cppdict::Dict& dict, Outer const& out) +{ + dict["inner"] = out.inner; + dict["meta"]["name"] = out.name; +} +template +void deserialize(cppdict::Dict const& dict, Outer& out) +{ + out.inner = dict["inner"].template to(); + out.name = dict["meta"]["name"].template to(); +} +} // namespace nested + + +TEST_CASE("custom types nest", "[cppconfig]") +{ + using MyDict + = cppdict::Dict, nested::Inner, nested::Outer>; + + nested::Outer const outer {}; + MyDict md; + md["outer"] = outer; + md["inner"] = nested::Inner {}; + + auto const bytes = to_bytes(md); + REQUIRE(json::from_cbor(bytes)["root"]["outer"][0] == "Outer"); + + auto const loaded = from_bytes(bytes); + REQUIRE(loaded["outer"].to() == outer); + REQUIRE(loaded["inner"].to() == nested::Inner {}); +} + + +struct Unnamed1 +{ +}; +struct Unnamed2 +{ +}; +template +void serialize(cppdict::Dict&, Unnamed1 const&) +{ +} +template +void deserialize(cppdict::Dict const&, Unnamed1&) +{ +} +template +void serialize(cppdict::Dict&, Unnamed2 const&) +{ +} +template +void deserialize(cppdict::Dict const&, Unnamed2&) +{ +} + + +TEST_CASE("cbor errors fail loudly", "[cppconfig]") +{ + using MyDict = cppdict::Dict; + + SECTION("missing file") + { + REQUIRE_THROWS(load_config("does/not/exist.cbor")); + } + + SECTION("empty leaf") + { + MyDict md; + md["a"]["b"]; + REQUIRE_THROWS(save_config("outfile.empty_leaf.cbor", md)); + } + + SECTION("empty config round trips") + { + save_config("outfile.empty.cbor", MyDict {}); + REQUIRE(load_config("outfile.empty.cbor").isEmpty()); + } + + SECTION("empty map round trips as a map") + { + MyDict md; + md["a"]["b"].data = MyDict::node_t {}; + md["c"] = 1; + save_config("outfile.empty_map.cbor", md); + auto const loaded = load_config("outfile.empty_map.cbor"); + REQUIRE(loaded["a"]["b"].isNode()); + REQUIRE(loaded["c"].to() == 1); + } + + SECTION("std::array round trips, length mismatch throws") + { + using ArrDict = cppdict::Dict>; + using ArrDict2 = cppdict::Dict>; + ArrDict ad; + ad["arr"] = std::array { 1, 2, 3 }; + save_config("outfile.array.cbor", ad); + REQUIRE(load_config("outfile.array.cbor")["arr"].to>() + == std::array { 1, 2, 3 }); + REQUIRE_THROWS(load_config("outfile.array.cbor")); + } + + SECTION("leaf type missing from the reading Dict") + { + cppdict::Dict> md; + md["v"] = std::vector { 1 }; + REQUIRE_THROWS(from_bytes(to_bytes(md))); + } + + SECTION("integer out of range") + { + auto const doc = json { { "format", "cppconfig" }, { "version", format_version }, + { "root", { { "x", json::array({ "i8", 300 }) } } } }; + REQUIRE_THROWS(from_bytes>(json::to_cbor(doc))); + } + + SECTION("not a cppconfig document") + { + REQUIRE_THROWS(from_bytes(json::to_cbor(json { { "a", 1 } }))); + } + + SECTION("ambiguous unnamed custom types") + { + cppdict::Dict md; + md["a"] = 1; + REQUIRE_THROWS_AS(to_bytes(md), std::logic_error); + } + + SECTION("truncated file") + { + std::string const file("outfile.truncated.cbor"); + MyDict md; + md["key"] = std::string { "Value" }; + save_config(file, md); + { + std::ifstream in { file, std::ios::binary }; + std::string bytes { std::istreambuf_iterator(in), {} }; + std::ofstream { file, std::ios::binary }.write(bytes.data(), bytes.size() - 2); + } + REQUIRE_THROWS(load_config(file)); + } +} From 0749cde6558d824b3051b183751dba20d8bf563a Mon Sep 17 00:00:00 2001 From: PhilipDeegan Date: Thu, 19 Nov 2026 14:37:28 +0100 Subject: [PATCH 2/2] cbor: basic types round trip test, author --- include/cppconfig/io/cbor.hpp | 4 ++-- tests/cbor/test.cpp | 36 ++++++++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/include/cppconfig/io/cbor.hpp b/include/cppconfig/io/cbor.hpp index 629045a..fb45bc2 100644 --- a/include/cppconfig/io/cbor.hpp +++ b/include/cppconfig/io/cbor.hpp @@ -16,8 +16,8 @@ -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -------------------------------------------------------------------------------*/ -/*-- Author : Alexis Jeandet --- Mail : alexis.jeandet@lpp.polytechnique.fr +/*-- Author : Philip Deegan +-- Mail : philip.deegan@gmail.com ----------------------------------------------------------------------------*/ #pragma once diff --git a/tests/cbor/test.cpp b/tests/cbor/test.cpp index 370249f..912b4ec 100644 --- a/tests/cbor/test.cpp +++ b/tests/cbor/test.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -59,16 +60,37 @@ TEST_CASE("file is plain CBOR", "[cppconfig]") } -TEST_CASE("leaf type order does not matter", "[cppconfig]") +TEST_CASE("basic types round trip", "[cppconfig]") { - cppdict::Dict md; - md["i"] = std::int64_t { 1 } << 40; - md["d"] = 0.5; + using MyDict = cppdict::Dict; + + MyDict md; + md["b"] = true; + md["i8"] = std::numeric_limits::min(); + md["i16"] = std::numeric_limits::min(); + md["i32"] = std::numeric_limits::min(); + md["i64"] = std::numeric_limits::min(); + md["u8"] = std::numeric_limits::max(); + md["u16"] = std::numeric_limits::max(); + md["u32"] = std::numeric_limits::max(); + md["u64"] = std::numeric_limits::max(); + md["f"] = 1.5f; + md["d"] = 0.1; md["s"] = std::string { "s" }; - auto const loaded = from_bytes>(to_bytes(md)); - REQUIRE(loaded["i"].to() == std::int64_t { 1 } << 40); - REQUIRE(loaded["d"].to() == 0.5); + auto const loaded = from_bytes(to_bytes(md)); + REQUIRE(loaded["b"].to() == true); + REQUIRE(loaded["i8"].to() == std::numeric_limits::min()); + REQUIRE(loaded["i16"].to() == std::numeric_limits::min()); + REQUIRE(loaded["i32"].to() == std::numeric_limits::min()); + REQUIRE(loaded["i64"].to() == std::numeric_limits::min()); + REQUIRE(loaded["u8"].to() == std::numeric_limits::max()); + REQUIRE(loaded["u16"].to() == std::numeric_limits::max()); + REQUIRE(loaded["u32"].to() == std::numeric_limits::max()); + REQUIRE(loaded["u64"].to() == std::numeric_limits::max()); + REQUIRE(loaded["f"].to() == 1.5f); + REQUIRE(loaded["d"].to() == 0.1); REQUIRE(loaded["s"].to() == "s"); }