Skip to content

Commit 8a75449

Browse files
committed
Add byte container support for ubjson.
1 parent 9fda30b commit 8a75449

2 files changed

Lines changed: 64 additions & 1 deletion

File tree

include/rfl/ubjson/read.hpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <jsoncons_ext/ubjson/decode_ubjson.hpp>
88
#include <string>
99

10+
#include "../concepts.hpp"
1011
#include "../Processors.hpp"
1112
#include "../internal/wrap_in_rfl_array_t.hpp"
1213
#include "Parser.hpp"
@@ -19,7 +20,7 @@ using InputVarType = typename Reader::InputVarType;
1920

2021
/// Parses an object from UBJSON using reflection.
2122
template <class T, class... Ps>
22-
Result<internal::wrap_in_rfl_array_t<T>> read(const std::vector<char>& _bytes) {
23+
Result<internal::wrap_in_rfl_array_t<T>> read(const ContiguousByteContainer auto& _bytes) {
2324
// TODO: Use a non-throwing decode_ubjson(), pending https://github.com/danielaparker/jsoncons/issues/615
2425
try {
2526
auto val = jsoncons::ubjson::decode_ubjson<jsoncons::json>(_bytes);
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <algorithm>
2+
#include <array>
3+
#include <rfl/ubjson.hpp>
4+
5+
#include <gtest/gtest.h>
6+
7+
// Make sure things still compile when
8+
// rfl.hpp is included after rfl/ubjson.hpp.
9+
#include <rfl.hpp>
10+
11+
namespace test_read_byte_containers
12+
{
13+
14+
struct TestBall
15+
{
16+
float radius;
17+
float mass;
18+
};
19+
20+
TEST(ubjson, test_read_from_byte_view)
21+
{
22+
TestBall b = {
23+
.radius = 1.5f,
24+
.mass = 2.5f,
25+
};
26+
27+
// TODO: Write directly into desired container, once rfl::ubjson::write supports it.
28+
std::vector<char> rfl_buffer = rfl::ubjson::write(b);
29+
30+
std::array<std::byte, 64> my_buffer;
31+
std::transform(rfl_buffer.begin(), rfl_buffer.end(), my_buffer.begin(),
32+
[](char c) { return static_cast<std::byte>(c); });
33+
34+
std::basic_string_view<std::byte> byte_view(my_buffer.data(), rfl_buffer.size());
35+
36+
auto result = rfl::ubjson::read<TestBall>(byte_view);
37+
EXPECT_TRUE(result);
38+
EXPECT_EQ(result->radius, 1.5f);
39+
EXPECT_EQ(result->mass, 2.5f);
40+
}
41+
42+
TEST(ubjson, test_read_from_uint8_array)
43+
{
44+
TestBall b = {
45+
.radius = 4.5f,
46+
.mass = 5.5f,
47+
};
48+
49+
// TODO: Write directly into desired container, once rfl::ubjson::write supports it.
50+
std::vector<char> rfl_buffer = rfl::ubjson::write(b);
51+
52+
std::array<std::uint8_t, 64> my_buffer;
53+
std::transform(rfl_buffer.begin(), rfl_buffer.end(), my_buffer.begin(),
54+
[](char c) { return static_cast<std::uint8_t>(c); });
55+
56+
auto result = rfl::ubjson::read<TestBall>(my_buffer);
57+
EXPECT_TRUE(result);
58+
EXPECT_EQ(result->radius, 4.5f);
59+
EXPECT_EQ(result->mass, 5.5f);
60+
}
61+
62+
} // namespace test_read_byte_containers

0 commit comments

Comments
 (0)