xrpld
Loading...
Searching...
No Matches
Slice.cpp
1#include <xrpl/basics/Slice.h>
2
3#include <gtest/gtest.h>
4
5#include <array>
6#include <cstddef>
7#include <cstdint>
8
9using namespace xrpl;
10
11static std::uint8_t const kData[] = {
12 0xa8, 0xa1, 0x38, 0x45, 0x23, 0xec, 0xe4, 0x23, 0x71, 0x6d, 0x2a, 0x18, 0xb4, 0x70, 0xcb, 0xf5,
13 0xac, 0x2d, 0x89, 0x4d, 0x19, 0x9c, 0xf0, 0x2c, 0x15, 0xd1, 0xf9, 0x9b, 0x66, 0xd2, 0x30, 0xd3};
14
15TEST(Slice, equality_and_inequality)
16{
17 Slice const s0{};
18
19 EXPECT_EQ(s0.size(), 0);
20 EXPECT_EQ(s0.data(), nullptr);
21 EXPECT_EQ(s0, s0);
22
23 // Test slices of equal and unequal size pointing to same data:
24 for (std::size_t i = 0; i != sizeof(kData); ++i)
25 {
26 Slice const s1{kData, i};
27
28 EXPECT_EQ(s1.size(), i);
29 EXPECT_NE(s1.data(), nullptr);
30
31 if (i == 0)
32 {
33 EXPECT_EQ(s1, s0);
34 }
35 else
36 {
37 EXPECT_NE(s1, s0);
38 }
39
40 for (std::size_t j = 0; j != sizeof(kData); ++j)
41 {
42 Slice const s2{kData, j};
43
44 if (i == j)
45 {
46 EXPECT_EQ(s1, s2);
47 }
48 else
49 {
50 EXPECT_NE(s1, s2);
51 }
52 }
53 }
54
55 // Test slices of equal size but pointing to different data:
56 std::array<std::uint8_t, sizeof(kData)> a{};
57 std::array<std::uint8_t, sizeof(kData)> b{};
58
59 for (std::size_t i = 0; i != sizeof(kData); ++i)
60 a[i] = b[i] = kData[i];
61
62 EXPECT_EQ(makeSlice(a), makeSlice(b));
63 b[7]++;
64 EXPECT_NE(makeSlice(a), makeSlice(b));
65 a[7]++;
66 EXPECT_EQ(makeSlice(a), makeSlice(b));
67}
68
69TEST(Slice, indexing)
70{
71 Slice const s{kData, sizeof(kData)};
72
73 for (std::size_t i = 0; i != sizeof(kData); ++i)
74 EXPECT_EQ(s[i], kData[i]);
75}
76
77TEST(Slice, advancing)
78{
79 for (std::size_t i = 0; i < sizeof(kData); ++i)
80 {
81 for (std::size_t j = 0; i + j < sizeof(kData); ++j)
82 {
83 Slice s(kData + i, sizeof(kData) - i);
84 s += j;
85
86 EXPECT_EQ(s.data(), kData + i + j);
87 EXPECT_EQ(s.size(), sizeof(kData) - i - j);
88 }
89 }
90}
An immutable linear range of bytes.
Definition Slice.h:26
std::uint8_t const * data() const noexcept
Return a pointer to beginning of the storage.
Definition Slice.h:78
std::size_t size() const noexcept
Returns the number of bytes in the storage.
Definition Slice.h:61
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
std::enable_if_t< std::is_same_v< T, char >||std::is_same_v< T, unsigned char >, Slice > makeSlice(std::array< T, N > const &a)
Definition Slice.h:215