scalar_range json serialization

This commit is contained in:
Green Sky 2021-03-19 16:28:40 +01:00
parent 84bd115ebd
commit 0a1895d0be
4 changed files with 84 additions and 0 deletions

View File

@ -5,6 +5,19 @@ add_library(std_utils INTERFACE)
target_include_directories(std_utils INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/src")
##############################
# curr only scalar_range
add_library(std_utils_serialize INTERFACE)
target_include_directories(std_utils_serialize INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/src")
target_link_libraries(std_utils_serialize INTERFACE
nlohmann_json::nlohmann_json
)
##############################
if (BUILD_TESTING)
add_subdirectory(test)
endif()

View File

@ -0,0 +1,26 @@
#pragma once
#include <nlohmann/json.hpp>
#include "../scalar_range2.hpp"
namespace MM {
template<typename T>
void to_json(nlohmann::json& j, const ScalarRange2<T>& r) {
j = nlohmann::json{
{"min", r.min()},
{"max", r.max()}
};
}
template<typename T>
void from_json(const nlohmann::json& j, ScalarRange2<T>& r) {
j.at("min").get_to(r.min());
j.at("max").get_to(r.max());
r.sanitize();
}
} // MM

View File

@ -1,5 +1,6 @@
add_executable(std_utils_test
scalar_range2_test.cpp
scalar_range2_json_test.cpp
)
target_include_directories(std_utils_test PRIVATE ".")
@ -9,6 +10,7 @@ target_link_libraries(std_utils_test
gmock
std_utils
std_utils_serialize
)
add_test(NAME std_utils_test COMMAND std_utils_test)

View File

@ -0,0 +1,43 @@
#include <gtest/gtest.h>
#include <mm/scalar_range2.hpp>
#include <mm/serialize/json_scalar_range2.hpp>
#include <cstdint>
TEST(std_utils_scalar_range2_json, signed_integer) {
MM::ScalarRange2<int8_t> r8 {-4, 100};
nlohmann::json j = r8;
ASSERT_EQ(j["min"], -4);
ASSERT_EQ(j["max"], 100);
MM::ScalarRange2<int8_t> r8_2 = j;
ASSERT_EQ(r8_2.min(), -4);
ASSERT_EQ(r8_2.max(), 100);
}
TEST(std_utils_scalar_range2_json, unsigned_integer) {
MM::ScalarRange2<uint8_t> r8 {4, 100};
nlohmann::json j = r8;
ASSERT_EQ(j["min"], 4);
ASSERT_EQ(j["max"], 100);
MM::ScalarRange2<uint8_t> r8_2 = j;
ASSERT_EQ(r8_2.min(), 4);
ASSERT_EQ(r8_2.max(), 100);
}
TEST(std_utils_scalar_range2_json, floating) {
MM::ScalarRange2<float> r {-4.3f, 100.f};
nlohmann::json j = r;
ASSERT_EQ(j["min"], -4.3f);
ASSERT_EQ(j["max"], 100.f);
MM::ScalarRange2<float> r_2 = j;
ASSERT_EQ(r_2.min(), -4.3f);
ASSERT_EQ(r_2.max(), 100.f);
}