simplesync/test/simplesync_test.cpp
2024-01-23 18:27:49 +01:00

96 lines
3.3 KiB
C++

#include <cstdint>
#include <cstring>
#include <gtest/gtest.h>
#include <iostream>
#include "simplesync.hpp"
TEST(simplesync_test, varint) {
uint8_t buf[1024];
for (int i = -999999; i < 999999; i += 29) {
int offset = simplesync::encode_varint(i, buf, sizeof(buf));
ASSERT_LE(1, offset);
for (int o = 0; o < offset - 1; o += 1)
EXPECT_FALSE(buf[o] & 0x80) << "offset:" << offset << " " << (uint32_t)(buf[o] & 0x7F);
EXPECT_TRUE(buf[offset - 1] & 0x80)
<< "offset:" << offset << " " << (uint32_t)(buf[offset - 1] & 0x7F);
int out;
offset = simplesync::decode_varint(buf, sizeof(buf), out);
ASSERT_LE(1, offset);
ASSERT_EQ(out, i);
}
}
TEST(simplesync_test, cobs_encode) {
uint8_t buf_raw[] = {0x11, 0x22, 0x00, 0x33};
uint8_t buf_coded[] = {0x03, 0x11, 0x22, 0x02, 0x33, 0x00};
uint8_t buf[sizeof(buf_coded) + 1];
unsigned int buf_used = simplesync::cobs_encode(buf_raw, sizeof(buf_raw), buf, sizeof(buf));
ASSERT_EQ(buf_used, sizeof(buf_coded));
ASSERT_EQ(0, memcmp(buf_coded, buf, sizeof(buf_coded)));
unsigned int buf_out_used = sizeof(buf);
unsigned int buf_in_used = sizeof(buf_coded);
int decoded_bytes = simplesync::cobs_decode(buf_coded, buf_in_used, buf, buf_out_used);
ASSERT_EQ(decoded_bytes, sizeof(buf_raw));
ASSERT_EQ(buf_used, sizeof(buf_coded));
ASSERT_EQ(buf_out_used, sizeof(buf_raw));
ASSERT_EQ(0, memcmp(buf_raw, buf, sizeof(buf_raw)));
}
uint8_t stream_buf[1024];
unsigned int buf_size = sizeof(stream_buf);
unsigned int buf_used = 0;
TEST(simplesync_test, encode_decode) {
buf_used = 0;
int time = 0;
typedef simplesync::SimpleSync<int, int, 512, true> S;
S s_send(
[](uint8_t *buf, unsigned int buf_size) {
memcpy(stream_buf + buf_used, buf, buf_size);
buf_used += buf_size;
return 0;
},
[&]() { return time; });
S s_recv([](uint8_t *, unsigned int) { return 0; }, [&]() { return time; });
int n1 = 4;
int n2 = 2;
std::string str = "hello";
S::NumberPtrPeriodic(s_send, "n1", &n1, 0);
S::NumberPtrPeriodic(s_send, "n2", &n2, 2);
S::TextPtrPeriodic(s_send, "s1", &str, 0);
for (time = 0; time < 5; time += 1) {
buf_used = 0;
s_send.update();
s_send.update();
for (unsigned int i = 0; i < buf_used; i += 1)
std::cout << std::hex << (int)stream_buf[i] << " ";
std::cout << std::dec << std::endl;
unsigned int parsed = 0;
for (unsigned int i = 1; i <= buf_used; i += 1)
parsed += s_recv.parse_stream_buf(stream_buf + parsed, i - parsed);
ASSERT_EQ(parsed, buf_used);
}
str = "hollo2";
ASSERT_NE(s_recv.get_number((char *)"n1"), nullptr);
ASSERT_EQ(*s_recv.get_number((char *)"n1"), n1);
ASSERT_NE(s_recv.get_number((char *)"n2"), nullptr);
ASSERT_EQ(*s_recv.get_number((char *)"n2"), n2);
ASSERT_STREQ(s_send.get_string((char *)"s1")->c_str(), "hollo2");
ASSERT_STREQ(str.c_str(), "hollo2");
ASSERT_STREQ(s_recv.get_string((char *)"s1")->c_str(), "hello");
ASSERT_EQ(4, n1);
ASSERT_EQ(2, n2);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}