Skip to content

Commit dd257a8

Browse files
Ian-Flurydcorbeil
andauthored
Fix cbor encoding for uint64_t's (#442)
Signed-off-by: David Corbeil <[email protected]> Signed-off-by: Ian Flury <[email protected]> Co-authored-by: David Corbeil <[email protected]>
1 parent 750e67d commit dd257a8

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

include/rfl/cbor/Writer.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,8 @@ class Writer {
103103
encoder_->bool_value(_var);
104104
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
105105
encoder_->double_value(static_cast<double>(_var));
106+
} else if constexpr (std::is_unsigned<std::remove_cvref_t<T>>()) {
107+
encoder_->uint64_value(static_cast<std::uint64_t>(_var));
106108
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
107109
encoder_->int64_value(static_cast<std::int64_t>(_var));
108110
} else {

tests/cbor/test_integers.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <gtest/gtest.h>
2+
3+
#include <rfl/cbor.hpp>
4+
5+
namespace test_integers {
6+
7+
TEST(cbor, test_integers_signedness) {
8+
9+
static constexpr uint64_t BIG_INT = 0xffffffffffffffff;
10+
11+
struct Unsigned {
12+
uint64_t u64;
13+
};
14+
15+
struct Signed {
16+
int64_t i64;
17+
};
18+
19+
std::vector<char> unsigned_buffer = rfl::cbor::write(Unsigned{BIG_INT});
20+
std::vector<unsigned char> unsigned_expected = {
21+
0xA1, 0x63, 0x75, 0x36, 0x34,
22+
0x1B, // Per RFC 8949, Initial byte '0x1B' indicates "unsigned integer (eight-byte uint64_t follows)"
23+
// See: https://www.rfc-editor.org/rfc/rfc8949.html#section-appendix.b
24+
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
25+
};
26+
27+
EXPECT_EQ(std::vector<char>(unsigned_expected.begin(), unsigned_expected.end()), unsigned_buffer);
28+
29+
std::vector<char> signed_buffer = rfl::cbor::write(Signed{static_cast<int64_t>(BIG_INT)});
30+
std::vector<unsigned char> signed_expected = {
31+
0xA1, 0x63, 0x69, 0x36, 0x34,
32+
0x20 // Per RFC 8949, Initial byte '0x20' indicates "negative integer -1-0x00..-1-0x17 (-1..-24)"
33+
// See: https://www.rfc-editor.org/rfc/rfc8949.html#section-appendix.b
34+
};
35+
36+
EXPECT_EQ(std::vector<char>(signed_expected.begin(), signed_expected.end()), signed_buffer);
37+
}
38+
39+
} // namespace test_integers

0 commit comments

Comments
 (0)