Debian Codegraph @

src/SPERR/test_scripts/graveyard/bit_buffer_unit_test.cpp

raw
1 #include "bit_buffer.h"
2 #include "gtest/gtest.h"
3
4 #include <random>
5 #include <memory>
6 #include <cstdio>
7
8 namespace
9 {
10
11 class bit_buffer_tester
12 {
13 public:
14 bool compare() const
15 {
16 if( a.empty() != b.empty() ) {
17 printf("a.empty() = %d, b.empty() = %d\n", a.empty(), b.empty());
18 return false;
19 }
20
21 if( a.size() != b.size() ) {
22 printf("a.size() = %ld, b.size() = %ld\n", a.size(), b.size());
23 return false;
24 }
25
26 for( size_t i = 0; i < a.size(); i++ ) {
27 if( a[i] != b.peek(i) ) {
28 printf("a[i] = %d, b.peek(i) = %d\n", int(a[i]), int(b.peek(i)));
29 return false;
30 }
31 }
32
33 return true;
34 }
35
36 void test( size_t N )
37 {
38 for( long i = 0; i < N; i++ ) {
39 auto action = distrib( gen );
40 // 60% chance: push
41 if( action < 60 ) {
42 a.push_back( i % 2 );
43 b.push_back( i % 2 );
44 }
45 // 25% chance: peek
46 else if( action < 85 ) {
47 if( a.empty() ) continue;
48 auto idx = i % a.size();
49 if( a[idx] != b.peek(idx) )
50 printf("a[idx] = %d, b.peek(idx) = %d\n", int(a[idx]), int(b.peek(idx)));
51 }
52 // 10% chance: populate from raw memory
53 else if( action < 95 ) {
54 if( b.empty() ) continue;
55 const auto nbits = b.size();
56 const auto nbytes = b.data_size();
57 auto tmp = std::make_unique<uint8_t[]>( nbytes );
58
59 const uint8_t* data = b.data();
60 for( size_t ii = 0; ii < nbytes; ii++ )
61 tmp[ii] = data[ii];
62
63 // Test the status of b.populate(). If failure, then
64 // trigger a comparison that's def. gonna fail.
65 if( !b.populate( tmp.get(), nbytes, nbits ) ) {
66 b.clear();
67 break;
68 }
69 }
70 // 3% chance: clear
71 else if( action < 98 ) {
72 a.clear();
73 b.clear();
74 }
75 // 2% chance: access memory
76 else {
77 ptr = b.data();
78 }
79 }
80 }
81
82 private:
83 std::vector<bool> a;
84 speck::bit_buffer b;
85 const uint8_t* ptr = nullptr;
86
87 std::random_device rd; //Will be used to obtain a seed for the random number engine
88 std::mt19937 gen{rd()}; //Standard mersenne_twister_engine seeded with rd()
89 std::uniform_int_distribution<> distrib{0, 99};
90 };
91
92
93 TEST( bit_buffer, hundreds )
94 {
95 const size_t mult = 100;
96 bit_buffer_tester tester;
97 for( size_t i = 1; i < 10; i++ ) {
98 tester.test( i * mult );
99 EXPECT_EQ( tester.compare(), true );
100 }
101 }
102
103
104 TEST( bit_buffer, thousands )
105 {
106 const size_t mult = 1000;
107 bit_buffer_tester tester;
108 for( size_t i = 1; i < 10; i++ ) {
109 tester.test( i * mult );
110 EXPECT_EQ( tester.compare(), true );
111 }
112 }
113
114
115 TEST( bit_buffer, many_operations )
116 {
117 const size_t mult = 10000;
118 bit_buffer_tester tester;
119 for( size_t i = 1; i < 50; i++ ) {
120 tester.test( i * mult );
121 EXPECT_EQ( tester.compare(), true );
122 }
123 }
124
125 }