From b34fddbe945339bd41394578c68bfa61e9b5d1b1 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Thu, 29 Aug 2024 12:32:41 +0300 Subject: [PATCH] add StructMapper.setChars, getChars --- src/data/StructMapper.cpp | 23 +++++++++++++++++++++++ src/data/StructMapper.hpp | 2 ++ test/data/StructMapper.cpp | 5 ++++- 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/data/StructMapper.cpp b/src/data/StructMapper.cpp index 238fd665..1e26f816 100644 --- a/src/data/StructMapper.cpp +++ b/src/data/StructMapper.cpp @@ -103,6 +103,18 @@ void StructMapping::setNumber( } } +void StructMapping::setChars( + ubyte* dst, std::string_view value, const std::string& name +) { + const auto& field = requreField(name); + if (field.type != FieldType::CHAR) { + throw std::runtime_error("'char' field type required"); + } + auto ptr = reinterpret_cast(dst + field.offset); + std::memcpy(ptr, value.data(), + std::min(value.size(), static_cast(field.elements))); +} + template static T get_int(const ubyte* src) { return dataio::le2h(*reinterpret_cast(src)); @@ -160,3 +172,14 @@ number_t StructMapping::getNumber( } throw std::runtime_error("type error"); } + +std::string_view StructMapping::getChars( + const ubyte* src, const std::string& name +) const { + const auto& field = requreField(name); + if (field.type != FieldType::CHAR) { + throw std::runtime_error("'char' field type required"); + } + auto ptr = src + field.offset; + return std::string_view(reinterpret_cast(ptr), field.elements); +} diff --git a/src/data/StructMapper.hpp b/src/data/StructMapper.hpp index 32c33ed1..358105f9 100644 --- a/src/data/StructMapper.hpp +++ b/src/data/StructMapper.hpp @@ -57,9 +57,11 @@ namespace data { integer_t getInteger(const ubyte* src, const std::string& name, int index=0) const; number_t getNumber(const ubyte* src, const std::string& name, int index=0) const; + std::string_view getChars(const ubyte* src, const std::string& name) const; void setInteger(ubyte* dst, integer_t value, const std::string& name, int index=0); void setNumber(ubyte* dst, number_t value, const std::string& name, int index=0); + void setChars(ubyte* dst, std::string_view value, const std::string& name); int size() const { return totalSize; diff --git a/test/data/StructMapper.cpp b/test/data/StructMapper.cpp index 60c874b1..67aeb97b 100644 --- a/test/data/StructMapper.cpp +++ b/test/data/StructMapper.cpp @@ -9,7 +9,7 @@ TEST(StructMapper, ReadWrite) { std::vector fields { Field {FieldType::I8, "a", 1}, - Field {FieldType::I32, "b", 1}, + Field {FieldType::CHAR, "s", 4}, Field {FieldType::F32, "f", 1}, }; auto mapping = StructMapping::create(fields); @@ -20,4 +20,7 @@ TEST(StructMapper, ReadWrite) { mapping.setNumber(buffer, 3.141592f, "f"); EXPECT_FLOAT_EQ(mapping.getNumber(buffer, "f"), 3.141592f); + + mapping.setChars(buffer, "hello", "s"); + EXPECT_EQ(mapping.getChars(buffer, "s"), "hell"); }