• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     https://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <iomanip>
18 #include <sstream>
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 
23 #include "cppbor.h"
24 #include "cppbor_parse.h"
25 
26 using namespace cppbor;
27 using namespace std;
28 
29 using ::testing::_;
30 using ::testing::AllOf;
31 using ::testing::ByRef;
32 using ::testing::InSequence;
33 using ::testing::IsNull;
34 using ::testing::NotNull;
35 using ::testing::Return;
36 using ::testing::Truly;
37 using ::testing::Unused;
38 
hexDump(const string & str)39 string hexDump(const string& str) {
40     stringstream s;
41     for (auto c : str) {
42         s << setfill('0') << setw(2) << hex << (static_cast<unsigned>(c) & 0xff);
43     }
44     return s.str();
45 }
46 
TEST(SimpleValueTest,UnsignedValueSizes)47 TEST(SimpleValueTest, UnsignedValueSizes) {
48     // Check that unsigned integers encode to correct lengths, and that encodedSize() is correct.
49     vector<pair<uint64_t /* value */, size_t /* expected encoded size */>> testCases{
50             {0, 1},
51             {1, 1},
52             {23, 1},
53             {24, 2},
54             {255, 2},
55             {256, 3},
56             {65535, 3},
57             {65536, 5},
58             {4294967295, 5},
59             {4294967296, 9},
60             {std::numeric_limits<uint64_t>::max(), 9},
61     };
62     for (auto& testCase : testCases) {
63         Uint val(testCase.first);
64         EXPECT_EQ(testCase.second, val.encodedSize()) << "Wrong size for value " << testCase.first;
65         EXPECT_EQ(val.encodedSize(), val.toString().size())
66                 << "encodedSize and encoding disagree for value " << testCase.first;
67     }
68 }
69 
TEST(SimpleValueTest,UnsignedValueEncodings)70 TEST(SimpleValueTest, UnsignedValueEncodings) {
71     EXPECT_EQ("\x00"s, Uint(0u).toString());
72     EXPECT_EQ("\x01"s, Uint(1u).toString());
73     EXPECT_EQ("\x0a"s, Uint(10u).toString());
74     EXPECT_EQ("\x17"s, Uint(23u).toString());
75     EXPECT_EQ("\x18\x18"s, Uint(24u).toString());
76     EXPECT_EQ("\x18\x19"s, Uint(25u).toString());
77     EXPECT_EQ("\x18\x64"s, Uint(100u).toString());
78     EXPECT_EQ("\x19\x03\xe8"s, Uint(1000u).toString());
79     EXPECT_EQ("\x1a\x00\x0f\x42\x40"s, Uint(1000000u).toString());
80     EXPECT_EQ("\x1b\x00\x00\x00\xe8\xd4\xa5\x10\x00"s, Uint(1000000000000u).toString());
81     EXPECT_EQ("\x1B\x7f\xff\xff\xff\xff\xff\xff\xff"s,
82               Uint(std::numeric_limits<int64_t>::max()).toString());
83 }
84 
TEST(SimpleValueTest,NegativeValueEncodings)85 TEST(SimpleValueTest, NegativeValueEncodings) {
86     EXPECT_EQ("\x20"s, Nint(-1).toString());
87     EXPECT_EQ("\x28"s, Nint(-9).toString());
88     EXPECT_EQ("\x29"s, Nint(-10).toString());
89     EXPECT_EQ("\x36"s, Nint(-23).toString());
90     EXPECT_EQ("\x37"s, Nint(-24).toString());
91     EXPECT_EQ("\x38\x18"s, Nint(-25).toString());
92     EXPECT_EQ("\x38\x62"s, Nint(-99).toString());
93     EXPECT_EQ("\x38\x63"s, Nint(-100).toString());
94     EXPECT_EQ("\x39\x03\xe6"s, Nint(-999).toString());
95     EXPECT_EQ("\x39\x03\xe7"s, Nint(-1000).toString());
96     EXPECT_EQ("\x3a\x00\x0f\x42\x3F"s, Nint(-1000000).toString());
97     EXPECT_EQ("\x3b\x00\x00\x00\xe8\xd4\xa5\x0f\xff"s, Nint(-1000000000000).toString());
98     EXPECT_EQ("\x3B\x7f\xff\xff\xff\xff\xff\xff\xff"s,
99               Nint(std::numeric_limits<int64_t>::min()).toString());
100 }
101 
TEST(SimpleValueDeathTest,NegativeValueEncodings)102 TEST(SimpleValueDeathTest, NegativeValueEncodings) {
103     EXPECT_DEATH(Nint(0), "");
104     EXPECT_DEATH(Nint(1), "");
105 }
106 
TEST(SimpleValueTest,BooleanEncodings)107 TEST(SimpleValueTest, BooleanEncodings) {
108     EXPECT_EQ("\xf4"s, Bool(false).toString());
109     EXPECT_EQ("\xf5"s, Bool(true).toString());
110 }
111 
TEST(SimpleValueTest,NullEncodings)112 TEST(SimpleValueTest, NullEncodings) {
113     EXPECT_EQ("\xf6"s, Null().toString());
114 }
115 
TEST(SimpleValueTest,ByteStringEncodings)116 TEST(SimpleValueTest, ByteStringEncodings) {
117     EXPECT_EQ("\x40", Bstr("").toString());
118     EXPECT_EQ("\x41\x61", Bstr("a").toString());
119     EXPECT_EQ("\x41\x41", Bstr("A").toString());
120     EXPECT_EQ("\x44\x49\x45\x54\x46", Bstr("IETF").toString());
121     EXPECT_EQ("\x42\x22\x5c", Bstr("\"\\").toString());
122     EXPECT_EQ("\x42\xc3\xbc", Bstr("\xc3\xbc").toString());
123     EXPECT_EQ("\x43\xe6\xb0\xb4", Bstr("\xe6\xb0\xb4").toString());
124     EXPECT_EQ("\x44\xf0\x90\x85\x91", Bstr("\xf0\x90\x85\x91").toString());
125     EXPECT_EQ("\x44\x01\x02\x03\x04", Bstr("\x01\x02\x03\x04").toString());
126     EXPECT_EQ("\x44\x40\x40\x40\x40", Bstr("@@@@").toString());
127 }
128 
TEST(SimpleValueTest,TextStringEncodings)129 TEST(SimpleValueTest, TextStringEncodings) {
130     EXPECT_EQ("\x60"s, Tstr("").toString());
131     EXPECT_EQ("\x61\x61"s, Tstr("a").toString());
132     EXPECT_EQ("\x61\x41"s, Tstr("A").toString());
133     EXPECT_EQ("\x64\x49\x45\x54\x46"s, Tstr("IETF").toString());
134     EXPECT_EQ("\x62\x22\x5c"s, Tstr("\"\\").toString());
135     EXPECT_EQ("\x62\xc3\xbc"s, Tstr("\xc3\xbc").toString());
136     EXPECT_EQ("\x63\xe6\xb0\xb4"s, Tstr("\xe6\xb0\xb4").toString());
137     EXPECT_EQ("\x64\xf0\x90\x85\x91"s, Tstr("\xf0\x90\x85\x91").toString());
138     EXPECT_EQ("\x64\x01\x02\x03\x04"s, Tstr("\x01\x02\x03\x04").toString());
139 }
140 
TEST(SimpleValueTest,SemanticTagEncoding)141 TEST(SimpleValueTest, SemanticTagEncoding) {
142     EXPECT_EQ("\xDB\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x63\x41\x45\x53"s,
143               SemanticTag(std::numeric_limits<uint64_t>::max(), "AES").toString());
144 }
145 
TEST(SimpleValueTest,NestedSemanticTagEncoding)146 TEST(SimpleValueTest, NestedSemanticTagEncoding) {
147     auto tripleTagged =
148             SemanticTag(254,
149                         SemanticTag(1,                                                 //
150                                     SemanticTag(std::numeric_limits<uint64_t>::max(),  //
151                                                 "AES")));
152     EXPECT_EQ("\xD8\xFE\xC1\xDB\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x63\x41\x45\x53"s,
153               tripleTagged.toString());
154 }
155 
TEST(SimpleValueTest,ViewByteStringEncodings)156 TEST(SimpleValueTest, ViewByteStringEncodings) {
157     EXPECT_EQ("\x40", ViewBstr("").toString());
158     EXPECT_EQ("\x41\x61", ViewBstr("a").toString());
159     EXPECT_EQ("\x41\x41", ViewBstr("A").toString());
160     EXPECT_EQ("\x44\x49\x45\x54\x46", ViewBstr("IETF").toString());
161     EXPECT_EQ("\x42\x22\x5c", ViewBstr("\"\\").toString());
162     EXPECT_EQ("\x42\xc3\xbc", ViewBstr("\xc3\xbc").toString());
163     EXPECT_EQ("\x43\xe6\xb0\xb4", ViewBstr("\xe6\xb0\xb4").toString());
164     EXPECT_EQ("\x44\xf0\x90\x85\x91", ViewBstr("\xf0\x90\x85\x91").toString());
165     EXPECT_EQ("\x44\x01\x02\x03\x04", ViewBstr("\x01\x02\x03\x04").toString());
166     EXPECT_EQ("\x44\x40\x40\x40\x40", ViewBstr("@@@@").toString());
167 }
168 
TEST(SimpleValueTest,ViewTextStringEncodings)169 TEST(SimpleValueTest, ViewTextStringEncodings) {
170     EXPECT_EQ("\x60"s, ViewTstr("").toString());
171     EXPECT_EQ("\x61\x61"s, ViewTstr("a").toString());
172     EXPECT_EQ("\x61\x41"s, ViewTstr("A").toString());
173     EXPECT_EQ("\x64\x49\x45\x54\x46"s, ViewTstr("IETF").toString());
174     EXPECT_EQ("\x62\x22\x5c"s, ViewTstr("\"\\").toString());
175     EXPECT_EQ("\x62\xc3\xbc"s, ViewTstr("\xc3\xbc").toString());
176     EXPECT_EQ("\x63\xe6\xb0\xb4"s, ViewTstr("\xe6\xb0\xb4").toString());
177     EXPECT_EQ("\x64\xf0\x90\x85\x91"s, ViewTstr("\xf0\x90\x85\x91").toString());
178     EXPECT_EQ("\x64\x01\x02\x03\x04"s, ViewTstr("\x01\x02\x03\x04").toString());
179 }
180 
TEST(IsIteratorPairOverTest,All)181 TEST(IsIteratorPairOverTest, All) {
182     EXPECT_TRUE((
183             details::is_iterator_pair_over<pair<string::iterator, string::iterator>, char>::value));
184     EXPECT_TRUE((details::is_iterator_pair_over<pair<string::const_iterator, string::iterator>,
185                                                 char>::value));
186     EXPECT_TRUE((details::is_iterator_pair_over<pair<string::iterator, string::const_iterator>,
187                                                 char>::value));
188     EXPECT_TRUE((details::is_iterator_pair_over<pair<char*, char*>, char>::value));
189     EXPECT_TRUE((details::is_iterator_pair_over<pair<const char*, char*>, char>::value));
190     EXPECT_TRUE((details::is_iterator_pair_over<pair<char*, const char*>, char>::value));
191     EXPECT_FALSE((details::is_iterator_pair_over<pair<string::iterator, string::iterator>,
192                                                  uint8_t>::value));
193     EXPECT_FALSE((details::is_iterator_pair_over<pair<char*, char*>, uint8_t>::value));
194     EXPECT_TRUE((details::is_iterator_pair_over<
195                  pair<vector<uint8_t>::iterator, vector<uint8_t>::iterator>, uint8_t>::value));
196     EXPECT_TRUE((details::is_iterator_pair_over<
197                  pair<vector<uint8_t>::const_iterator, vector<uint8_t>::iterator>,
198                  uint8_t>::value));
199     EXPECT_TRUE((details::is_iterator_pair_over<
200                  pair<vector<uint8_t>::iterator, vector<uint8_t>::const_iterator>,
201                  uint8_t>::value));
202     EXPECT_TRUE((details::is_iterator_pair_over<pair<uint8_t*, uint8_t*>, uint8_t>::value));
203     EXPECT_TRUE((details::is_iterator_pair_over<pair<const uint8_t*, uint8_t*>, uint8_t>::value));
204     EXPECT_TRUE((details::is_iterator_pair_over<pair<uint8_t*, const uint8_t*>, uint8_t>::value));
205     EXPECT_FALSE((details::is_iterator_pair_over<
206                   pair<vector<uint8_t>::iterator, vector<uint8_t>::iterator>, char>::value));
207     EXPECT_FALSE((details::is_iterator_pair_over<pair<uint8_t*, const uint8_t*>, char>::value));
208 }
209 
TEST(IsUniquePtrSubclassOf,All)210 TEST(IsUniquePtrSubclassOf, All) {
211     EXPECT_TRUE((details::is_unique_ptr_of_subclass_of_v<Item, std::unique_ptr<Bool>>::value));
212     EXPECT_TRUE((details::is_unique_ptr_of_subclass_of_v<Item, std::unique_ptr<Map>>::value));
213     EXPECT_TRUE((details::is_unique_ptr_of_subclass_of_v<Item, std::unique_ptr<Array>>::value));
214     EXPECT_TRUE(
215             (details::is_unique_ptr_of_subclass_of_v<Item, std::unique_ptr<SemanticTag>>::value));
216     EXPECT_FALSE(
217             (details::is_unique_ptr_of_subclass_of_v<std::string, std::unique_ptr<Bool>>::value));
218     EXPECT_FALSE((
219             details::is_unique_ptr_of_subclass_of_v<uint8_t, std::unique_ptr<std::string>>::value));
220 }
221 
TEST(MakeEntryTest,Boolean)222 TEST(MakeEntryTest, Boolean) {
223     EXPECT_EQ("\xf4"s, details::makeItem(false)->toString());
224 }
225 
TEST(MakeEntryTest,Null)226 TEST(MakeEntryTest, Null) {
227     EXPECT_EQ("\xf6"s, details::makeItem(nullptr)->toString());
228 }
229 
TEST(MakeEntryTest,Integers)230 TEST(MakeEntryTest, Integers) {
231     EXPECT_EQ("\x00"s, details::makeItem(static_cast<uint8_t>(0))->toString());
232     EXPECT_EQ("\x00"s, details::makeItem(static_cast<uint16_t>(0))->toString());
233     EXPECT_EQ("\x00"s, details::makeItem(static_cast<uint32_t>(0))->toString());
234     EXPECT_EQ("\x00"s, details::makeItem(static_cast<uint64_t>(0))->toString());
235     EXPECT_EQ("\x00"s, details::makeItem(static_cast<int8_t>(0))->toString());
236     EXPECT_EQ("\x00"s, details::makeItem(static_cast<int16_t>(0))->toString());
237     EXPECT_EQ("\x00"s, details::makeItem(static_cast<int32_t>(0))->toString());
238     EXPECT_EQ("\x00"s, details::makeItem(static_cast<int64_t>(0))->toString());
239     EXPECT_EQ("\x20"s, details::makeItem(static_cast<int8_t>(-1))->toString());
240     EXPECT_EQ("\x20"s, details::makeItem(static_cast<int16_t>(-1))->toString());
241     EXPECT_EQ("\x20"s, details::makeItem(static_cast<int32_t>(-1))->toString());
242     EXPECT_EQ("\x20"s, details::makeItem(static_cast<int64_t>(-1))->toString());
243 
244     EXPECT_EQ("\x1b\xff\xff\xff\xff\xff\xff\xff\xff"s,
245               details::makeItem(static_cast<uint64_t>(std::numeric_limits<uint64_t>::max()))
246                       ->toString());
247 }
248 
TEST(MakeEntryTest,StdStrings)249 TEST(MakeEntryTest, StdStrings) {
250     string s1("hello");
251     const string s2("hello");
252     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s1)->toString());  // copy of string
253     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s,
254               details::makeItem(s2)->toString());  // copy of const string
255     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s,
256               details::makeItem(std::move(s1))->toString());  // move string
257     EXPECT_EQ(0U, s1.size());                                 // Prove string was moved, not copied.
258 }
259 
TEST(MakeEntryTest,StdStringViews)260 TEST(MakeEntryTest, StdStringViews) {
261     string_view s1("hello");
262     const string_view s2("hello");
263     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s1)->toString());
264     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s2)->toString());
265 }
266 
TEST(MakeEntryTest,CStrings)267 TEST(MakeEntryTest, CStrings) {
268     char s1[] = "hello";
269     const char s2[] = "hello";
270     const char* s3 = "hello";
271     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s1)->toString());
272     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s2)->toString());
273     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(s3)->toString());
274 }
275 
TEST(MakeEntryTest,StringIteratorPairs)276 TEST(MakeEntryTest, StringIteratorPairs) {
277     // Use iterators from string to prove that "real" iterators work
278     string s1 = "hello"s;
279     pair<string::iterator, string::iterator> p1 = make_pair(s1.begin(), s1.end());
280 
281     const pair<string::iterator, string::iterator> p2 = p1;
282     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(p1)->toString());
283     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(p2)->toString());
284 
285     // Use char*s  as iterators
286     const char* s2 = "hello";
287     pair p3 = make_pair(s2, s2 + 5);
288     const pair p4 = p3;
289     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(p3)->toString());
290     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(p4)->toString());
291 }
292 
TEST(MakeEntryTest,ByteStrings)293 TEST(MakeEntryTest, ByteStrings) {
294     vector<uint8_t> v1 = {0x00, 0x01, 0x02};
295     const vector<uint8_t> v2 = {0x00, 0x01, 0x02};
296     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(v1)->toString());  // copy of vector
297     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(v2)->toString());  // copy of const vector
298     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(std::move(v1))->toString());  // move vector
299     EXPECT_EQ(0U, v1.size());  // Prove vector was moved, not copied.
300 }
301 
TEST(MakeEntryTest,ByteStringIteratorPairs)302 TEST(MakeEntryTest, ByteStringIteratorPairs) {
303     using vec = vector<uint8_t>;
304     using iter = vec::iterator;
305     vec v1 = {0x00, 0x01, 0x02};
306     pair<iter, iter> p1 = make_pair(v1.begin(), v1.end());
307     const pair<iter, iter> p2 = make_pair(v1.begin(), v1.end());
308     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p1)->toString());
309     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p2)->toString());
310 
311     // Use uint8_t*s as iterators
312     uint8_t v2[] = {0x00, 0x01, 0x02};
313     uint8_t* v3 = v2;
314     pair<uint8_t*, uint8_t*> p3 = make_pair(v2, v2 + 3);
315     const pair<uint8_t*, uint8_t*> p4 = make_pair(v2, v2 + 3);
316     pair<uint8_t*, uint8_t*> p5 = make_pair(v3, v3 + 3);
317     const pair<uint8_t*, uint8_t*> p6 = make_pair(v3, v3 + 3);
318     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p3)->toString());
319     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p4)->toString());
320     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p5)->toString());
321     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(p6)->toString());
322 }
323 
TEST(MakeEntryTest,ByteStringBuffers)324 TEST(MakeEntryTest, ByteStringBuffers) {
325     uint8_t v1[] = {0x00, 0x01, 0x02};
326     EXPECT_EQ("\x43\x00\x01\x02"s, details::makeItem(make_pair(v1, 3))->toString());
327 }
328 
TEST(MakeEntryTest,ItemPointer)329 TEST(MakeEntryTest, ItemPointer) {
330     Uint* p1 = new Uint(0);
331     EXPECT_EQ("\x00"s, details::makeItem(p1)->toString());
332     EXPECT_EQ("\x60"s, details::makeItem(new Tstr(string()))->toString());
333 }
334 
TEST(MakeEntryTest,ItemReference)335 TEST(MakeEntryTest, ItemReference) {
336     Tstr str("hello"s);
337     Tstr& strRef = str;
338     const Tstr& strConstRef = str;
339     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(str)->toString());
340     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(strRef)->toString());
341     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(strConstRef)->toString());
342     EXPECT_EQ("\x65\x68\x65\x6c\x6c\x6f"s, details::makeItem(std::move(str))->toString());
343     EXPECT_EQ("\x60"s, details::makeItem(str)->toString());  // Prove that it moved
344 
345     EXPECT_EQ("\x00"s, details::makeItem(Uint(0))->toString());
346 
347     EXPECT_EQ("\x43\x00\x01\x02"s,
348               details::makeItem(Bstr(vector<uint8_t>{0x00, 0x01, 0x02}))->toString());
349 
350     EXPECT_EQ("\x80"s, details::makeItem(Array())->toString());
351     EXPECT_EQ("\xa0"s, details::makeItem(Map())->toString());
352 }
353 
TEST(CompoundValueTest,ArrayOfInts)354 TEST(CompoundValueTest, ArrayOfInts) {
355     EXPECT_EQ("\x80"s, Array().toString());
356     Array(Uint(0)).toString();
357 
358     EXPECT_EQ("\x81\x00"s, Array(Uint(0U)).toString());
359     EXPECT_EQ("\x82\x00\x01"s, Array(Uint(0), Uint(1)).toString());
360     EXPECT_EQ("\x83\x00\x01\x38\x62"s, Array(Uint(0), Uint(1), Nint(-99)).toString());
361 
362     EXPECT_EQ("\x81\x00"s, Array(0).toString());
363     EXPECT_EQ("\x82\x00\x01"s, Array(0, 1).toString());
364     EXPECT_EQ("\x83\x00\x01\x38\x62"s, Array(0, 1, -99).toString());
365 }
366 
TEST(CompoundValueTest,MapOfInts)367 TEST(CompoundValueTest, MapOfInts) {
368     EXPECT_EQ("\xA0"s, Map().toString());
369     EXPECT_EQ("\xA1\x00\x01"s, Map(Uint(0), Uint(1)).toString());
370     // Maps with an odd number of arguments will fail to compile.  Uncomment the next lines to test.
371     // EXPECT_EQ("\xA1\x00"s, Map(Int(0)).toString());
372     // EXPECT_EQ("\xA1\x00\x01\x02"s, Map(Int(0), Int(1), Int(2)).toString());
373 }
374 
TEST(CompoundValueTest,MixedArray)375 TEST(CompoundValueTest, MixedArray) {
376     vector<uint8_t> vec = {3, 2, 1};
377     EXPECT_EQ("\x84\x01\x20\x43\x03\x02\x01\x65\x68\x65\x6C\x6C\x6F"s,
378               Array(Uint(1), Nint(-1), Bstr(vec), Tstr("hello")).toString());
379 
380     EXPECT_EQ("\x84\x01\x20\x43\x03\x02\x01\x65\x68\x65\x6C\x6C\x6F"s,
381               Array(1, -1, vec, "hello").toString());
382 }
383 
TEST(CompoundValueTest,MixedMap)384 TEST(CompoundValueTest, MixedMap) {
385     vector<uint8_t> vec = {3, 2, 1};
386     EXPECT_EQ("\xA2\x01\x20\x43\x03\x02\x01\x65\x68\x65\x6C\x6C\x6F"s,
387               Map(Uint(1), Nint(-1), Bstr(vec), Tstr("hello")).toString());
388 
389     EXPECT_EQ("\xA2\x01\x20\x43\x03\x02\x01\x65\x68\x65\x6C\x6C\x6F"s,
390               Map(1, -1, vec, "hello").toString());
391 }
392 
TEST(CompoundValueTest,NestedStructures)393 TEST(CompoundValueTest, NestedStructures) {
394     vector<uint8_t> vec = {3, 2, 1};
395 
396     string expectedEncoding =
397             "\xA2\x66\x4F\x75\x74\x65\x72\x31\x82\xA2\x66\x49\x6E\x6E\x65\x72\x31\x18\x63\x66\x49"
398             "\x6E"
399             "\x6E\x65\x72\x32\x43\x03\x02\x01\x63\x66\x6F\x6F\x66\x4F\x75\x74\x65\x72\x32\x0A"s;
400 
401     // Do it with explicity-created Items
402     EXPECT_EQ(expectedEncoding,
403               Map(Tstr("Outer1"),
404                   Array(  //
405                           Map(Tstr("Inner1"), Uint(99), Tstr("Inner2"), Bstr(vec)), Tstr("foo")),
406                   Tstr("Outer2"),  //
407                   Uint(10))
408                       .toString());
409     EXPECT_EQ(3U, vec.size());
410 
411     // Now just use convertible types
412     EXPECT_EQ(expectedEncoding, Map("Outer1",
413                                     Array(Map("Inner1", 99,  //
414                                               "Inner2", vec),
415                                           "foo"),
416                                     "Outer2", 10)
417                                         .toString());
418     EXPECT_EQ(3U, vec.size());
419 
420     // Finally, do it with the .add() method.  This is slightly less efficient, but has the
421     // advantage you can build a structure up incrementally, or somewhat fluently if you like.
422     // First, fluently.
423     EXPECT_EQ(expectedEncoding, Map().add("Outer1", Array().add(Map()  //
424                                                                         .add("Inner1", 99)
425                                                                         .add("Inner2", vec))
426                                                             .add("foo"))
427                                         .add("Outer2", 10)
428                                         .toString());
429     EXPECT_EQ(3U, vec.size());
430 
431     // Next, more incrementally
432     Array arr;
433     arr.add(Map()  //
434                     .add("Inner1", 99)
435                     .add("Inner2", vec))
436             .add("foo");
437     EXPECT_EQ(3U, vec.size());
438 
439     Map m;
440     m.add("Outer1", std::move(arr));  // Moving is necessary; Map and Array cannot be copied.
441     m.add("Outer2", 10);
442     auto s = m.toString();
443     EXPECT_EQ(expectedEncoding, s);
444 }
445 
TEST(EncodingMethodsTest,AllVariants)446 TEST(EncodingMethodsTest, AllVariants) {
447     Map map;
448     map.add("key1", Array().add(Map()  //
449                                         .add("key_a", 9999999)
450                                         .add("key_b", std::vector<uint8_t>{0x01, 0x02, 0x03})
451                                         .add("key_c", std::numeric_limits<uint64_t>::max())
452                                         .add("key_d", std::numeric_limits<int16_t>::min()))
453                             .add("foo"))
454             .add("key2", true)
455             .add("key3", SemanticTag(1, SemanticTag(987654321, "Zhai gana test")));
456 
457     std::vector<uint8_t> buf;
458     buf.resize(map.encodedSize());
459 
460     EXPECT_EQ(buf.data() + buf.size(), map.encode(buf.data(), buf.data() + buf.size()));
461 
462     EXPECT_EQ(buf, map.encode());
463 
464     std::vector<uint8_t> buf2;
465     map.encode(std::back_inserter(buf2));
466     EXPECT_EQ(buf, buf2);
467 
468     auto iter = buf.begin();
469     map.encode([&](uint8_t c) { EXPECT_EQ(c, *iter++); });
470 }
471 
TEST(EncodingMethodsTest,UintWithTooShortBuf)472 TEST(EncodingMethodsTest, UintWithTooShortBuf) {
473     Uint val(100000);
474     vector<uint8_t> buf(val.encodedSize() - 1);
475     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
476 }
477 
TEST(EncodingMethodsTest,TstrWithTooShortBuf)478 TEST(EncodingMethodsTest, TstrWithTooShortBuf) {
479     Tstr val("01234567890123456789012345"s);
480     vector<uint8_t> buf(1);
481     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
482 
483     buf.resize(val.encodedSize() - 1);
484     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
485 }
486 
TEST(EncodingMethodsTest,BstrWithTooShortBuf)487 TEST(EncodingMethodsTest, BstrWithTooShortBuf) {
488     Bstr val("01234567890123456789012345"s);
489     vector<uint8_t> buf(1);
490     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
491 
492     buf.resize(val.encodedSize() - 1);
493     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
494 }
495 
TEST(EncodingMethodsTest,ArrayWithTooShortBuf)496 TEST(EncodingMethodsTest, ArrayWithTooShortBuf) {
497     Array val("a", 5, -100);
498 
499     std::vector<uint8_t> buf(val.encodedSize() - 1);
500     EXPECT_EQ(nullptr, val.encode(buf.data(), buf.data() + buf.size()));
501 }
502 
TEST(EncodingMethodsTest,MapWithTooShortBuf)503 TEST(EncodingMethodsTest, MapWithTooShortBuf) {
504     Map map;
505     map.add("key1", Array().add(Map()  //
506                                         .add("key_a", 99)
507                                         .add("key_b", std::vector<uint8_t>{0x01, 0x02, 0x03}))
508                             .add("foo"))
509             .add("key2", true);
510 
511     std::vector<uint8_t> buf(map.encodedSize() - 1);
512     EXPECT_EQ(nullptr, map.encode(buf.data(), buf.data() + buf.size()));
513 }
514 
TEST(EncodingMethodsTest,SemanticTagWithTooShortBuf)515 TEST(EncodingMethodsTest, SemanticTagWithTooShortBuf) {
516     SemanticTag tag(4321, Array().add(Array().add("Qaiyrly kesh!").add("Kesh zharyq!").add("431"))
517                                   .add(Map().add("kilt_1", 777).add("kilt_2", 999)));
518     std::vector<uint8_t> buf(tag.encodedSize() - 1);
519     EXPECT_EQ(nullptr, tag.encode(buf.data(), buf.data() + buf.size()));
520 }
521 
TEST(EqualityTest,Uint)522 TEST(EqualityTest, Uint) {
523     Uint val(99);
524     EXPECT_EQ(val, Uint(99));
525 
526     EXPECT_NE(val, Uint(98));
527     EXPECT_NE(val, Nint(-1));
528     EXPECT_NE(val, Tstr("99"));
529     EXPECT_NE(val, Bstr("99"));
530     EXPECT_NE(val, Bool(false));
531     EXPECT_NE(val, Array(99, 1));
532     EXPECT_NE(val, Map(99, 1));
533     EXPECT_NE(val, ViewTstr("99"));
534     EXPECT_NE(val, ViewBstr("99"));
535 }
536 
TEST(EqualityTest,Nint)537 TEST(EqualityTest, Nint) {
538     Nint val(-1);
539     EXPECT_EQ(val, Nint(-1));
540 
541     EXPECT_NE(val, Uint(99));
542     EXPECT_NE(val, Nint(-4));
543     EXPECT_NE(val, Tstr("99"));
544     EXPECT_NE(val, Bstr("99"));
545     EXPECT_NE(val, Bool(false));
546     EXPECT_NE(val, Array(99));
547     EXPECT_NE(val, Map(99, 1));
548     EXPECT_NE(val, ViewTstr("99"));
549     EXPECT_NE(val, ViewBstr("99"));
550 }
551 
TEST(EqualityTest,Tstr)552 TEST(EqualityTest, Tstr) {
553     Tstr val("99");
554     EXPECT_EQ(val, Tstr("99"));
555 
556     EXPECT_NE(val, Uint(99));
557     EXPECT_NE(val, Nint(-1));
558     EXPECT_NE(val, Nint(-4));
559     EXPECT_NE(val, Tstr("98"));
560     EXPECT_NE(val, Bstr("99"));
561     EXPECT_NE(val, Bool(false));
562     EXPECT_NE(val, Array(99, 1));
563     EXPECT_NE(val, Map(99, 1));
564     EXPECT_NE(val, ViewTstr("99"));
565     EXPECT_NE(val, ViewBstr("99"));
566 }
567 
TEST(EqualityTest,Bstr)568 TEST(EqualityTest, Bstr) {
569     Bstr val("99");
570     EXPECT_EQ(val, Bstr("99"));
571 
572     EXPECT_NE(val, Uint(99));
573     EXPECT_NE(val, Nint(-1));
574     EXPECT_NE(val, Nint(-4));
575     EXPECT_NE(val, Tstr("99"));
576     EXPECT_NE(val, Bstr("98"));
577     EXPECT_NE(val, Bool(false));
578     EXPECT_NE(val, Array(99, 1));
579     EXPECT_NE(val, Map(99, 1));
580     EXPECT_NE(val, ViewTstr("99"));
581     EXPECT_NE(val, ViewBstr("99"));
582 }
583 
TEST(EqualityTest,Bool)584 TEST(EqualityTest, Bool) {
585     Bool val(false);
586     EXPECT_EQ(val, Bool(false));
587 
588     EXPECT_NE(val, Uint(99));
589     EXPECT_NE(val, Nint(-1));
590     EXPECT_NE(val, Nint(-4));
591     EXPECT_NE(val, Tstr("99"));
592     EXPECT_NE(val, Bstr("98"));
593     EXPECT_NE(val, Bool(true));
594     EXPECT_NE(val, Array(99, 1));
595     EXPECT_NE(val, Map(99, 1));
596     EXPECT_NE(val, ViewTstr("99"));
597     EXPECT_NE(val, ViewBstr("98"));
598 }
599 
TEST(EqualityTest,Array)600 TEST(EqualityTest, Array) {
601     Array val(99, 1);
602     EXPECT_EQ(val, Array(99, 1));
603 
604     EXPECT_NE(val, Uint(99));
605     EXPECT_NE(val, Nint(-1));
606     EXPECT_NE(val, Nint(-4));
607     EXPECT_NE(val, Tstr("99"));
608     EXPECT_NE(val, Bstr("98"));
609     EXPECT_NE(val, Bool(true));
610     EXPECT_NE(val, Array(99, 2));
611     EXPECT_NE(val, Array(98, 1));
612     EXPECT_NE(val, Array(99, 1, 2));
613     EXPECT_NE(val, Map(99, 1));
614     EXPECT_NE(val, ViewTstr("99"));
615     EXPECT_NE(val, ViewBstr("98"));
616 }
617 
TEST(EqualityTest,Map)618 TEST(EqualityTest, Map) {
619     Map val(99, 1);
620     EXPECT_EQ(val, Map(99, 1));
621 
622     EXPECT_NE(val, Uint(99));
623     EXPECT_NE(val, Nint(-1));
624     EXPECT_NE(val, Nint(-4));
625     EXPECT_NE(val, Tstr("99"));
626     EXPECT_NE(val, Bstr("98"));
627     EXPECT_NE(val, Bool(true));
628     EXPECT_NE(val, Array(99, 1));
629     EXPECT_NE(val, Map(99, 2));
630     EXPECT_NE(val, Map(99, 1, 99, 2));
631     EXPECT_NE(val, ViewTstr("99"));
632     EXPECT_NE(val, ViewBstr("98"));
633 }
634 
TEST(EqualityTest,Null)635 TEST(EqualityTest, Null) {
636     Null val;
637     EXPECT_EQ(val, Null());
638 
639     EXPECT_NE(val, Uint(99));
640     EXPECT_NE(val, Nint(-1));
641     EXPECT_NE(val, Nint(-4));
642     EXPECT_NE(val, Tstr("99"));
643     EXPECT_NE(val, Bstr("98"));
644     EXPECT_NE(val, Bool(true));
645     EXPECT_NE(val, Array(99, 1));
646     EXPECT_NE(val, Map(99, 2));
647     EXPECT_NE(val, Map(99, 1, 99, 2));
648     EXPECT_NE(val, ViewTstr("99"));
649     EXPECT_NE(val, ViewBstr("98"));
650 }
651 
TEST(EqualityTest,SemanticTag)652 TEST(EqualityTest, SemanticTag) {
653     SemanticTag val(215, Bstr("asd"));
654     EXPECT_EQ(val, SemanticTag(215, Bstr("asd")));
655 
656     EXPECT_NE(val, Uint(99));
657     EXPECT_NE(val, Nint(-1));
658     EXPECT_NE(val, Nint(-4));
659     EXPECT_NE(val, Tstr("99"));
660     EXPECT_NE(val, Bstr("98"));
661     EXPECT_NE(val, Bool(true));
662     EXPECT_NE(val, Array(99, 1));
663     EXPECT_NE(val, Map(99, 2));
664     EXPECT_NE(val, Null());
665 }
666 
TEST(EqualityTest,NestedSemanticTag)667 TEST(EqualityTest, NestedSemanticTag) {
668     SemanticTag val(238238, SemanticTag(215, Bstr("asd")));
669     EXPECT_EQ(val, SemanticTag(238238, SemanticTag(215, Bstr("asd"))));
670 
671     EXPECT_NE(val, Uint(99));
672     EXPECT_NE(val, Nint(-1));
673     EXPECT_NE(val, Nint(-4));
674     EXPECT_NE(val, Tstr("99"));
675     EXPECT_NE(val, Bstr("98"));
676     EXPECT_NE(val, Bool(true));
677     EXPECT_NE(val, Array(99, 1));
678     EXPECT_NE(val, Map(99, 2));
679     EXPECT_NE(val, Null());
680     EXPECT_NE(val, ViewTstr("99"));
681     EXPECT_NE(val, ViewBstr("98"));
682 }
683 
TEST(EqualityTest,ViewTstr)684 TEST(EqualityTest, ViewTstr) {
685     ViewTstr val("99");
686     EXPECT_EQ(val, ViewTstr("99"));
687 
688     EXPECT_NE(val, Uint(99));
689     EXPECT_NE(val, Nint(-1));
690     EXPECT_NE(val, Nint(-4));
691     EXPECT_NE(val, Tstr("99"));
692     EXPECT_NE(val, Bstr("99"));
693     EXPECT_NE(val, Bool(false));
694     EXPECT_NE(val, Array(99, 1));
695     EXPECT_NE(val, Map(99, 1));
696     EXPECT_NE(val, ViewTstr("98"));
697     EXPECT_NE(val, ViewBstr("99"));
698 }
699 
TEST(EqualityTest,ViewBstr)700 TEST(EqualityTest, ViewBstr) {
701     ViewBstr val("99");
702     EXPECT_EQ(val, ViewBstr("99"));
703 
704     EXPECT_NE(val, Uint(99));
705     EXPECT_NE(val, Nint(-1));
706     EXPECT_NE(val, Nint(-4));
707     EXPECT_NE(val, Tstr("99"));
708     EXPECT_NE(val, Bstr("99"));
709     EXPECT_NE(val, Bool(false));
710     EXPECT_NE(val, Array(99, 1));
711     EXPECT_NE(val, Map(99, 1));
712     EXPECT_NE(val, ViewTstr("99"));
713     EXPECT_NE(val, ViewBstr("98"));
714 }
715 
TEST(ConvertTest,Uint)716 TEST(ConvertTest, Uint) {
717     unique_ptr<Item> item = details::makeItem(10);
718 
719     EXPECT_EQ(UINT, item->type());
720     EXPECT_NE(nullptr, item->asInt());
721     EXPECT_NE(nullptr, item->asUint());
722     EXPECT_EQ(nullptr, item->asNint());
723     EXPECT_EQ(nullptr, item->asTstr());
724     EXPECT_EQ(nullptr, item->asBstr());
725     EXPECT_EQ(nullptr, item->asSimple());
726     EXPECT_EQ(nullptr, item->asMap());
727     EXPECT_EQ(nullptr, item->asArray());
728     EXPECT_EQ(nullptr, item->asViewTstr());
729     EXPECT_EQ(nullptr, item->asViewBstr());
730 
731     EXPECT_EQ(10, item->asInt()->value());
732     EXPECT_EQ(10, item->asUint()->value());
733 }
734 
TEST(ConvertTest,Nint)735 TEST(ConvertTest, Nint) {
736     unique_ptr<Item> item = details::makeItem(-10);
737 
738     EXPECT_EQ(NINT, item->type());
739     EXPECT_NE(nullptr, item->asInt());
740     EXPECT_EQ(nullptr, item->asUint());
741     EXPECT_NE(nullptr, item->asNint());
742     EXPECT_EQ(nullptr, item->asTstr());
743     EXPECT_EQ(nullptr, item->asBstr());
744     EXPECT_EQ(nullptr, item->asSimple());
745     EXPECT_EQ(nullptr, item->asMap());
746     EXPECT_EQ(nullptr, item->asArray());
747     EXPECT_EQ(nullptr, item->asViewTstr());
748     EXPECT_EQ(nullptr, item->asViewBstr());
749 
750     EXPECT_EQ(-10, item->asInt()->value());
751     EXPECT_EQ(-10, item->asNint()->value());
752 }
753 
TEST(ConvertTest,Tstr)754 TEST(ConvertTest, Tstr) {
755     unique_ptr<Item> item = details::makeItem("hello");
756 
757     EXPECT_EQ(TSTR, item->type());
758     EXPECT_EQ(nullptr, item->asInt());
759     EXPECT_EQ(nullptr, item->asUint());
760     EXPECT_EQ(nullptr, item->asNint());
761     EXPECT_NE(nullptr, item->asTstr());
762     EXPECT_EQ(nullptr, item->asBstr());
763     EXPECT_EQ(nullptr, item->asSimple());
764     EXPECT_EQ(nullptr, item->asMap());
765     EXPECT_EQ(nullptr, item->asArray());
766     EXPECT_EQ(nullptr, item->asViewTstr());
767     EXPECT_EQ(nullptr, item->asViewBstr());
768 
769     EXPECT_EQ("hello"s, item->asTstr()->value());
770 }
771 
TEST(ConvertTest,Bstr)772 TEST(ConvertTest, Bstr) {
773     vector<uint8_t> vec{0x23, 0x24, 0x22};
774     unique_ptr<Item> item = details::makeItem(vec);
775 
776     EXPECT_EQ(BSTR, item->type());
777     EXPECT_EQ(nullptr, item->asInt());
778     EXPECT_EQ(nullptr, item->asUint());
779     EXPECT_EQ(nullptr, item->asNint());
780     EXPECT_EQ(nullptr, item->asTstr());
781     EXPECT_NE(nullptr, item->asBstr());
782     EXPECT_EQ(nullptr, item->asSimple());
783     EXPECT_EQ(nullptr, item->asMap());
784     EXPECT_EQ(nullptr, item->asArray());
785     EXPECT_EQ(nullptr, item->asViewTstr());
786     EXPECT_EQ(nullptr, item->asViewBstr());
787 
788     EXPECT_EQ(vec, item->asBstr()->value());
789 }
790 
TEST(ConvertTest,Bool)791 TEST(ConvertTest, Bool) {
792     unique_ptr<Item> item = details::makeItem(false);
793 
794     EXPECT_EQ(SIMPLE, item->type());
795     EXPECT_EQ(nullptr, item->asInt());
796     EXPECT_EQ(nullptr, item->asUint());
797     EXPECT_EQ(nullptr, item->asNint());
798     EXPECT_EQ(nullptr, item->asTstr());
799     EXPECT_EQ(nullptr, item->asBstr());
800     EXPECT_NE(nullptr, item->asSimple());
801     EXPECT_EQ(nullptr, item->asMap());
802     EXPECT_EQ(nullptr, item->asArray());
803     EXPECT_EQ(nullptr, item->asViewTstr());
804     EXPECT_EQ(nullptr, item->asViewBstr());
805 
806     EXPECT_EQ(BOOLEAN, item->asSimple()->simpleType());
807     EXPECT_NE(nullptr, item->asSimple()->asBool());
808     EXPECT_EQ(nullptr, item->asSimple()->asNull());
809 
810     EXPECT_FALSE(item->asSimple()->asBool()->value());
811 }
812 
TEST(ConvertTest,Map)813 TEST(ConvertTest, Map) {
814     unique_ptr<Item> item(new Map);
815 
816     EXPECT_EQ(MAP, item->type());
817     EXPECT_EQ(nullptr, item->asInt());
818     EXPECT_EQ(nullptr, item->asUint());
819     EXPECT_EQ(nullptr, item->asNint());
820     EXPECT_EQ(nullptr, item->asTstr());
821     EXPECT_EQ(nullptr, item->asBstr());
822     EXPECT_EQ(nullptr, item->asSimple());
823     EXPECT_NE(nullptr, item->asMap());
824     EXPECT_EQ(nullptr, item->asArray());
825     EXPECT_EQ(nullptr, item->asViewTstr());
826     EXPECT_EQ(nullptr, item->asViewBstr());
827 
828     EXPECT_EQ(0U, item->asMap()->size());
829 }
830 
TEST(ConvertTest,Array)831 TEST(ConvertTest, Array) {
832     unique_ptr<Item> item(new Array);
833 
834     EXPECT_EQ(ARRAY, item->type());
835     EXPECT_EQ(nullptr, item->asInt());
836     EXPECT_EQ(nullptr, item->asUint());
837     EXPECT_EQ(nullptr, item->asNint());
838     EXPECT_EQ(nullptr, item->asTstr());
839     EXPECT_EQ(nullptr, item->asBstr());
840     EXPECT_EQ(nullptr, item->asSimple());
841     EXPECT_EQ(nullptr, item->asMap());
842     EXPECT_NE(nullptr, item->asArray());
843     EXPECT_EQ(nullptr, item->asViewTstr());
844     EXPECT_EQ(nullptr, item->asViewBstr());
845 
846     EXPECT_EQ(0U, item->asArray()->size());
847 }
848 
TEST(ConvertTest,SemanticTag)849 TEST(ConvertTest, SemanticTag) {
850     unique_ptr<Item> item(new SemanticTag(10, "DSA"));
851 
852     EXPECT_EQ(TSTR, item->type());
853     EXPECT_EQ(nullptr, item->asInt());
854     EXPECT_EQ(nullptr, item->asUint());
855     EXPECT_EQ(nullptr, item->asNint());
856     EXPECT_EQ(nullptr, item->asBstr());
857     EXPECT_EQ(nullptr, item->asSimple());
858     EXPECT_EQ(nullptr, item->asMap());
859     EXPECT_EQ(nullptr, item->asArray());
860     EXPECT_EQ(nullptr, item->asViewTstr());
861     EXPECT_EQ(nullptr, item->asViewBstr());
862 
863     // Both asTstr() (the contained type) and asSemanticTag() return non-null.
864     EXPECT_NE(nullptr, item->asTstr());
865     EXPECT_NE(nullptr, item->asSemanticTag());
866 
867     // asTtr() and asSemanticTag() actually return different objects.
868     EXPECT_NE(static_cast<Item*>(item->asTstr()), static_cast<Item*>(item->asSemanticTag()));
869 
870     EXPECT_EQ(1U, item->asSemanticTag()->size());
871     EXPECT_EQ("DSA", item->asTstr()->value());
872 
873     EXPECT_EQ(1U, item->semanticTagCount());
874     EXPECT_EQ(10U, item->semanticTag());
875 }
876 
TEST(ConvertTest,NestedSemanticTag)877 TEST(ConvertTest, NestedSemanticTag) {
878     unique_ptr<Item> item(new SemanticTag(40, new SemanticTag(10, "DSA")));
879 
880     EXPECT_EQ(TSTR, item->type());
881     EXPECT_EQ(nullptr, item->asInt());
882     EXPECT_EQ(nullptr, item->asUint());
883     EXPECT_EQ(nullptr, item->asNint());
884     EXPECT_EQ(nullptr, item->asBstr());
885     EXPECT_EQ(nullptr, item->asSimple());
886     EXPECT_EQ(nullptr, item->asMap());
887     EXPECT_EQ(nullptr, item->asArray());
888     EXPECT_EQ(nullptr, item->asViewTstr());
889     EXPECT_EQ(nullptr, item->asViewBstr());
890 
891     // Both asTstr() (the contained type) and asSemanticTag() return non-null.
892     EXPECT_NE(nullptr, item->asTstr());
893     EXPECT_NE(nullptr, item->asSemanticTag());
894 
895     // asTtr() and asSemanticTag() actually return different objects.  Note that there's no way to
896     // get a pointer to the "inner" SemanticTag object.  There shouldn't be any need to.
897     EXPECT_NE(static_cast<Item*>(item->asTstr()), static_cast<Item*>(item->asSemanticTag()));
898 
899     EXPECT_EQ(1U, item->asSemanticTag()->size());
900     EXPECT_EQ("DSA", item->asTstr()->value());
901 
902     EXPECT_EQ(2U, item->semanticTagCount());
903     EXPECT_EQ(10U, item->semanticTag(0));
904     EXPECT_EQ(40U, item->semanticTag(1));
905 }
906 
TEST(ConvertTest,Null)907 TEST(ConvertTest, Null) {
908     unique_ptr<Item> item(new Null);
909 
910     EXPECT_EQ(SIMPLE, item->type());
911     EXPECT_EQ(nullptr, item->asInt());
912     EXPECT_EQ(nullptr, item->asUint());
913     EXPECT_EQ(nullptr, item->asNint());
914     EXPECT_EQ(nullptr, item->asTstr());
915     EXPECT_EQ(nullptr, item->asBstr());
916     EXPECT_NE(nullptr, item->asSimple());
917     EXPECT_EQ(nullptr, item->asMap());
918     EXPECT_EQ(nullptr, item->asArray());
919     EXPECT_EQ(nullptr, item->asViewTstr());
920     EXPECT_EQ(nullptr, item->asViewBstr());
921 
922     EXPECT_EQ(NULL_T, item->asSimple()->simpleType());
923     EXPECT_EQ(nullptr, item->asSimple()->asBool());
924     EXPECT_NE(nullptr, item->asSimple()->asNull());
925 }
926 
TEST(ConvertTest,ViewTstr)927 TEST(ConvertTest, ViewTstr) {
928     unique_ptr<Item> item = details::makeItem(ViewTstr("hello"));
929 
930     EXPECT_EQ(TSTR, item->type());
931     EXPECT_EQ(nullptr, item->asInt());
932     EXPECT_EQ(nullptr, item->asUint());
933     EXPECT_EQ(nullptr, item->asNint());
934     EXPECT_EQ(nullptr, item->asTstr());
935     EXPECT_EQ(nullptr, item->asBstr());
936     EXPECT_EQ(nullptr, item->asSimple());
937     EXPECT_EQ(nullptr, item->asMap());
938     EXPECT_EQ(nullptr, item->asArray());
939     EXPECT_NE(nullptr, item->asViewTstr());
940     EXPECT_EQ(nullptr, item->asViewBstr());
941 
942     EXPECT_EQ("hello"sv, item->asViewTstr()->view());
943 }
944 
TEST(ConvertTest,ViewBstr)945 TEST(ConvertTest, ViewBstr) {
946     array<uint8_t, 3> vec{0x23, 0x24, 0x22};
947     basic_string_view sv(vec.data(), vec.size());
948     unique_ptr<Item> item = details::makeItem(ViewBstr(sv));
949 
950     EXPECT_EQ(BSTR, item->type());
951     EXPECT_EQ(nullptr, item->asInt());
952     EXPECT_EQ(nullptr, item->asUint());
953     EXPECT_EQ(nullptr, item->asNint());
954     EXPECT_EQ(nullptr, item->asTstr());
955     EXPECT_EQ(nullptr, item->asBstr());
956     EXPECT_EQ(nullptr, item->asSimple());
957     EXPECT_EQ(nullptr, item->asMap());
958     EXPECT_EQ(nullptr, item->asArray());
959     EXPECT_EQ(nullptr, item->asViewTstr());
960     EXPECT_NE(nullptr, item->asViewBstr());
961 
962     EXPECT_EQ(sv, item->asViewBstr()->view());
963 }
964 
TEST(CloningTest,Uint)965 TEST(CloningTest, Uint) {
966     Uint item(10);
967     auto clone = item.clone();
968     EXPECT_EQ(clone->type(), UINT);
969     EXPECT_NE(clone->asUint(), nullptr);
970     EXPECT_EQ(item, *clone->asUint());
971     EXPECT_EQ(*clone->asUint(), Uint(10));
972 }
973 
TEST(CloningTest,Nint)974 TEST(CloningTest, Nint) {
975     Nint item(-1000000);
976     auto clone = item.clone();
977     EXPECT_EQ(clone->type(), NINT);
978     EXPECT_NE(clone->asNint(), nullptr);
979     EXPECT_EQ(item, *clone->asNint());
980     EXPECT_EQ(*clone->asNint(), Nint(-1000000));
981 }
982 
TEST(CloningTest,Tstr)983 TEST(CloningTest, Tstr) {
984     Tstr item("qwertyasdfgh");
985     auto clone = item.clone();
986     EXPECT_EQ(clone->type(), TSTR);
987     EXPECT_NE(clone->asTstr(), nullptr);
988     EXPECT_EQ(item, *clone->asTstr());
989     EXPECT_EQ(*clone->asTstr(), Tstr("qwertyasdfgh"));
990 }
991 
TEST(CloningTest,Bstr)992 TEST(CloningTest, Bstr) {
993     Bstr item(std::vector<uint8_t>{1, 2, 3, 255, 0});
994     auto clone = item.clone();
995     EXPECT_EQ(clone->type(), BSTR);
996     EXPECT_NE(clone->asBstr(), nullptr);
997     EXPECT_EQ(item, *clone->asBstr());
998     EXPECT_EQ(*clone->asBstr(), Bstr(std::vector<uint8_t>{1, 2, 3, 255, 0}));
999 }
1000 
TEST(CloningTest,Array)1001 TEST(CloningTest, Array) {
1002     Array item(-1000000, 22222222, "item", Map(1, 2, 4, Array(1, "das", true, nullptr)),
1003                SemanticTag(16, "DATA")),
1004             copy(-1000000, 22222222, "item", Map(1, 2, 4, Array(1, "das", true, nullptr)),
1005                  SemanticTag(16, "DATA"));
1006     auto clone = item.clone();
1007     EXPECT_EQ(clone->type(), ARRAY);
1008     EXPECT_NE(clone->asArray(), nullptr);
1009     EXPECT_EQ(item, *clone->asArray());
1010     EXPECT_EQ(*clone->asArray(), copy);
1011 }
1012 
TEST(CloningTest,Map)1013 TEST(CloningTest, Map) {
1014     Map item("key", Array("value1", "value2", 3), 15, Null(), -5, 45),
1015             copy("key", Array("value1", "value2", 3), 15, Null(), -5, 45);
1016     auto clone = item.clone();
1017     EXPECT_EQ(clone->type(), MAP);
1018     EXPECT_NE(clone->asMap(), nullptr);
1019     EXPECT_EQ(item, *clone->asMap());
1020     EXPECT_EQ(*clone->asMap(), copy);
1021 }
1022 
TEST(CloningTest,Bool)1023 TEST(CloningTest, Bool) {
1024     Bool item(true);
1025     auto clone = item.clone();
1026     EXPECT_EQ(clone->type(), SIMPLE);
1027     EXPECT_NE(clone->asSimple(), nullptr);
1028     EXPECT_EQ(clone->asSimple()->simpleType(), BOOLEAN);
1029     EXPECT_NE(clone->asSimple()->asBool(), nullptr);
1030     EXPECT_EQ(item, *clone->asSimple()->asBool());
1031     EXPECT_EQ(*clone->asSimple()->asBool(), Bool(true));
1032 }
1033 
TEST(CloningTest,Null)1034 TEST(CloningTest, Null) {
1035     Null item;
1036     auto clone = item.clone();
1037     EXPECT_EQ(clone->type(), SIMPLE);
1038     EXPECT_NE(clone->asSimple(), nullptr);
1039     EXPECT_EQ(clone->asSimple()->simpleType(), NULL_T);
1040     EXPECT_NE(clone->asSimple()->asNull(), nullptr);
1041     EXPECT_EQ(item, *clone->asSimple()->asNull());
1042     EXPECT_EQ(*clone->asSimple()->asNull(), Null());
1043 }
1044 
TEST(CloningTest,SemanticTag)1045 TEST(CloningTest, SemanticTag) {
1046     SemanticTag item(96, Array(1, 2, 3, "entry", Map("key", "value")));
1047     SemanticTag copy(96, Array(1, 2, 3, "entry", Map("key", "value")));
1048 
1049     auto clone = item.clone();
1050     EXPECT_EQ(clone->type(), ARRAY);
1051     EXPECT_NE(clone->asSemanticTag(), nullptr);
1052     EXPECT_EQ(item, *clone->asSemanticTag());
1053     EXPECT_EQ(*clone->asSemanticTag(), copy);
1054 }
1055 
TEST(CloningTest,NestedSemanticTag)1056 TEST(CloningTest, NestedSemanticTag) {
1057     SemanticTag item(20,                          //
1058                      SemanticTag(30,              //
1059                                  SemanticTag(96,  //
1060                                              Array(1, 2, 3, "entry", Map("key", "value")))));
1061     SemanticTag copy(20,                          //
1062                      SemanticTag(30,              //
1063                                  SemanticTag(96,  //
1064                                              Array(1, 2, 3, "entry", Map("key", "value")))));
1065 
1066     auto clone = item.clone();
1067     EXPECT_EQ(clone->type(), ARRAY);
1068     EXPECT_NE(clone->asSemanticTag(), nullptr);
1069     EXPECT_EQ(item, *clone->asSemanticTag());
1070     EXPECT_EQ(*clone->asSemanticTag(), copy);
1071 }
1072 
TEST(CloningTest,ViewTstr)1073 TEST(CloningTest, ViewTstr) {
1074     ViewTstr item("qwertyasdfgh");
1075     auto clone = item.clone();
1076     EXPECT_EQ(clone->type(), TSTR);
1077     EXPECT_NE(clone->asViewTstr(), nullptr);
1078     EXPECT_EQ(item, *clone->asViewTstr());
1079     EXPECT_EQ(*clone->asViewTstr(), ViewTstr("qwertyasdfgh"));
1080 }
1081 
TEST(CloningTest,ViewBstr)1082 TEST(CloningTest, ViewBstr) {
1083     array<uint8_t, 5> vec{1, 2, 3, 255, 0};
1084     basic_string_view sv(vec.data(), vec.size());
1085     ViewBstr item(sv);
1086     auto clone = item.clone();
1087     EXPECT_EQ(clone->type(), BSTR);
1088     EXPECT_NE(clone->asViewBstr(), nullptr);
1089     EXPECT_EQ(item, *clone->asViewBstr());
1090     EXPECT_EQ(*clone->asViewBstr(), ViewBstr(sv));
1091 }
1092 
TEST(PrettyPrintingTest,NestedSemanticTag)1093 TEST(PrettyPrintingTest, NestedSemanticTag) {
1094     SemanticTag item(20,                          //
1095                      SemanticTag(30,              //
1096                                  SemanticTag(96,  //
1097                                              Array(1, 2, 3, "entry", Map("key", "value")))));
1098     EXPECT_EQ(prettyPrint(&item),
1099               "tag 20 tag 30 tag 96 [\n"
1100               "  1,\n"
1101               "  2,\n"
1102               "  3,\n"
1103               "  'entry',\n"
1104               "  {\n"
1105               "    'key' : 'value',\n"
1106               "  },\n"
1107               "]");
1108 }
1109 
TEST(MapCanonicalizationTest,CanonicalizationTest)1110 TEST(MapCanonicalizationTest, CanonicalizationTest) {
1111     Map map;
1112     map.add("hello", 1)
1113             .add("h", 1)
1114             .add(1, 1)
1115             .add(-4, 1)
1116             .add(-5, 1)
1117             .add(2, 1)
1118             .add("hellp", 1)
1119             .add(254, 1)
1120             .add(27, 1);
1121 
1122     EXPECT_EQ(prettyPrint(&map),
1123               "{\n"
1124               "  'hello' : 1,\n"
1125               "  'h' : 1,\n"
1126               "  1 : 1,\n"
1127               "  -4 : 1,\n"
1128               "  -5 : 1,\n"
1129               "  2 : 1,\n"
1130               "  'hellp' : 1,\n"
1131               "  254 : 1,\n"
1132               "  27 : 1,\n"
1133               "}");
1134 
1135     map.canonicalize();
1136 
1137     // Canonically ordered by key encoding.
1138     EXPECT_EQ(prettyPrint(&map),
1139               "{\n"
1140               "  1 : 1,\n"
1141               "  2 : 1,\n"
1142               "  -4 : 1,\n"
1143               "  -5 : 1,\n"
1144               "  27 : 1,\n"
1145               "  254 : 1,\n"
1146               "  'h' : 1,\n"
1147               "  'hello' : 1,\n"
1148               "  'hellp' : 1,\n"
1149               "}");
1150 }
1151 
TEST(MapCanonicalizationTest,DecanonicalizationTest)1152 TEST(MapCanonicalizationTest, DecanonicalizationTest) {
1153     Map map;
1154     map.add("hello", 1)
1155             .add("h", 1)
1156             .add(1, 1)
1157             .add(-4, 1)
1158             .add(-5, 1)
1159             .add(2, 1)
1160             .add("hellp", 1)
1161             .add(254, 1)
1162             .add(27, 1);
1163 
1164     EXPECT_FALSE(map.isCanonical());
1165     map.canonicalize();
1166     EXPECT_TRUE(map.isCanonical());
1167 
1168     /*
1169      * Any operation that could potentially mutate the contents of the map should mark it as
1170      * non-canonical.  This includes getting non-const iterators or using the non-const [] operator.
1171      */
1172 
1173     map.begin();
1174     EXPECT_FALSE(map.isCanonical());
1175 
1176     map.canonicalize();
1177     EXPECT_TRUE(map.isCanonical());
1178 
1179     map.end();  // Non-const map.end() invalidates canonicalization.
1180     EXPECT_FALSE(map.isCanonical());
1181 
1182     map.canonicalize();
1183     EXPECT_TRUE(map.isCanonical());
1184 
1185     map[0];  // Non-const map.operator[]() invalidates canonicalization.
1186     EXPECT_FALSE(map.isCanonical());
1187 }
1188 
TEST(MapCanonicalizationTest,RecursiveTest)1189 TEST(MapCanonicalizationTest, RecursiveTest) {
1190     auto map = Map()  //
1191                        .add("hello", 1)
1192                        .add("h", 1)
1193                        .add(1, 1)
1194                        .add(-4, Array(  //
1195                                         2, 1,
1196                                         Map()  //
1197                                                 .add("b", 1)
1198                                                 .add(Map()  //
1199                                                              .add("hello", "goodbye")
1200                                                              .add(1, 9)
1201                                                              .add(0, 3),
1202                                                      Map()  //
1203                                                              .add("b", 1)
1204                                                              .add("a", 2))))
1205                        .add(-5, 1)
1206                        .add(2, 1)
1207                        .add("hellp", 1)
1208                        .add(254, 1)
1209                        .add(27, 1);
1210 
1211     EXPECT_EQ(prettyPrint(&map),
1212               "{\n"
1213               "  'hello' : 1,\n"
1214               "  'h' : 1,\n"
1215               "  1 : 1,\n"
1216               "  -4 : [\n"
1217               "    2,\n"
1218               "    1,\n"
1219               "    {\n"
1220               "      'b' : 1,\n"
1221               "      {\n"
1222               "        'hello' : 'goodbye',\n"
1223               "        1 : 9,\n"
1224               "        0 : 3,\n"
1225               "      } : {\n"
1226               "        'b' : 1,\n"
1227               "        'a' : 2,\n"
1228               "      },\n"
1229               "    },\n"
1230               "  ],\n"
1231               "  -5 : 1,\n"
1232               "  2 : 1,\n"
1233               "  'hellp' : 1,\n"
1234               "  254 : 1,\n"
1235               "  27 : 1,\n"
1236               "}");
1237 
1238     map.canonicalize(true /* recurse */);
1239 
1240     EXPECT_EQ(prettyPrint(&map),
1241               "{\n"
1242               "  1 : 1,\n"
1243               "  2 : 1,\n"
1244               "  -4 : [\n"
1245               "    2,\n"
1246               "    1,\n"
1247               "    {\n"
1248               "      'b' : 1,\n"
1249               "      {\n"
1250               "        0 : 3,\n"
1251               "        1 : 9,\n"
1252               "        'hello' : 'goodbye',\n"
1253               "      } : {\n"
1254               "        'a' : 2,\n"
1255               "        'b' : 1,\n"
1256               "      },\n"
1257               "    },\n"
1258               "  ],\n"
1259               "  -5 : 1,\n"
1260               "  27 : 1,\n"
1261               "  254 : 1,\n"
1262               "  'h' : 1,\n"
1263               "  'hello' : 1,\n"
1264               "  'hellp' : 1,\n"
1265               "}");
1266 }
1267 
1268 class MockParseClient : public ParseClient {
1269   public:
1270     MOCK_METHOD4(item, ParseClient*(std::unique_ptr<Item>& item, const uint8_t* hdrBegin,
1271                                     const uint8_t* valueBegin, const uint8_t* end));
1272     MOCK_METHOD4(itemEnd, ParseClient*(std::unique_ptr<Item>& item, const uint8_t* hdrBegin,
1273                                        const uint8_t* valueBegin, const uint8_t* end));
1274     MOCK_METHOD2(error, void(const uint8_t* position, const std::string& errorMessage));
1275 };
1276 
1277 MATCHER_P(IsType, value, std::string("Type ") + (negation ? "doesn't match" : "matches")) {
1278     return arg->type() == value;
1279 }
1280 
1281 MATCHER_P(MatchesItem, value, "") {
1282     return arg && *arg == value;
1283 }
1284 
1285 MATCHER_P(IsArrayOfSize, value, "") {
1286     return arg->type() == ARRAY && arg->asArray()->size() == value;
1287 }
1288 
1289 MATCHER_P(IsSemanticTagOfValue, value, "") {
1290     return arg->semanticTagCount() == 1 && arg->semanticTag() == value;
1291 }
1292 
1293 MATCHER_P(IsMapOfSize, value, "") {
1294     return arg->type() == MAP && arg->asMap()->size() == value;
1295 }
1296 
TEST(StreamParseTest,Uint)1297 TEST(StreamParseTest, Uint) {
1298     MockParseClient mpc;
1299 
1300     Uint val(100);
1301     auto encoded = val.encode();
1302     uint8_t* encBegin = encoded.data();
1303     uint8_t* encEnd = encoded.data() + encoded.size();
1304 
1305     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encEnd, encEnd)).WillOnce(Return(&mpc));
1306     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1307     EXPECT_CALL(mpc, error(_, _)).Times(0);
1308 
1309     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1310 }
1311 
TEST(StreamParseTest,Nint)1312 TEST(StreamParseTest, Nint) {
1313     MockParseClient mpc;
1314 
1315     Nint val(-10);
1316     auto encoded = val.encode();
1317     uint8_t* encBegin = encoded.data();
1318     uint8_t* encEnd = encoded.data() + encoded.size();
1319 
1320     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encEnd, encEnd)).WillOnce(Return(&mpc));
1321 
1322     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1323     EXPECT_CALL(mpc, error(_, _)).Times(0);
1324 
1325     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1326 }
1327 
TEST(StreamParseTest,Bool)1328 TEST(StreamParseTest, Bool) {
1329     MockParseClient mpc;
1330 
1331     Bool val(true);
1332     auto encoded = val.encode();
1333     uint8_t* encBegin = encoded.data();
1334     uint8_t* encEnd = encoded.data() + encoded.size();
1335 
1336     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encEnd, encEnd)).WillOnce(Return(&mpc));
1337     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1338     EXPECT_CALL(mpc, error(_, _)).Times(0);
1339 
1340     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1341 }
1342 
TEST(StreamParseTest,Null)1343 TEST(StreamParseTest, Null) {
1344     MockParseClient mpc;
1345 
1346     Null val;
1347     auto encoded = val.encode();
1348     uint8_t* encBegin = encoded.data();
1349     uint8_t* encEnd = encoded.data() + encoded.size();
1350 
1351     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encEnd, encEnd)).WillOnce(Return(&mpc));
1352     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1353     EXPECT_CALL(mpc, error(_, _)).Times(0);
1354 
1355     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1356 }
1357 
TEST(StreamParseTest,Tstr)1358 TEST(StreamParseTest, Tstr) {
1359     MockParseClient mpc;
1360 
1361     Tstr val("Hello");
1362     auto encoded = val.encode();
1363     uint8_t* encBegin = encoded.data();
1364     uint8_t* encEnd = encoded.data() + encoded.size();
1365 
1366     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encBegin + 1, encEnd)).WillOnce(Return(&mpc));
1367     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1368     EXPECT_CALL(mpc, error(_, _)).Times(0);
1369 
1370     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1371 }
1372 
TEST(StreamParseTest,Bstr)1373 TEST(StreamParseTest, Bstr) {
1374     MockParseClient mpc;
1375 
1376     Bstr val("Hello");
1377     auto encoded = val.encode();
1378     uint8_t* encBegin = encoded.data();
1379     uint8_t* encEnd = encoded.data() + encoded.size();
1380 
1381     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encBegin + 1, encEnd)).WillOnce(Return(&mpc));
1382     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1383     EXPECT_CALL(mpc, error(_, _)).Times(0);
1384 
1385     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1386 }
1387 
TEST(StreamParseTest,Array)1388 TEST(StreamParseTest, Array) {
1389     MockParseClient mpc;
1390 
1391     Array val("Hello", 4, Array(-9, "Goodbye"), std::numeric_limits<uint64_t>::max());
1392     ASSERT_NE(val[2]->asArray(), nullptr);
1393     const Array& interior = *(val[2]->asArray());
1394     auto encoded = val.encode();
1395     uint8_t* encBegin = encoded.data();
1396     uint8_t* encEnd = encoded.data() + encoded.size();
1397 
1398     {
1399         InSequence s;
1400         const uint8_t* pos = encBegin;
1401         EXPECT_CALL(mpc, item(IsArrayOfSize(val.size()), pos, pos + 1, pos + 1))
1402                 .WillOnce(Return(&mpc));
1403         ++pos;
1404         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[0])), pos, pos + 1, pos + 6))
1405                 .WillOnce(Return(&mpc));
1406         pos += 6;
1407         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[1])), pos, pos + 1, pos + 1))
1408                 .WillOnce(Return(&mpc));
1409         ++pos;
1410         const uint8_t* innerArrayBegin = pos;
1411         EXPECT_CALL(mpc, item(IsArrayOfSize(interior.size()), pos, pos + 1, pos + 1))
1412                 .WillOnce(Return(&mpc));
1413         ++pos;
1414         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*interior[0])), pos, pos + 1, pos + 1))
1415                 .WillOnce(Return(&mpc));
1416         ++pos;
1417         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*interior[1])), pos, pos + 1, pos + 8))
1418                 .WillOnce(Return(&mpc));
1419         pos += 8;
1420         EXPECT_CALL(mpc, itemEnd(IsArrayOfSize(interior.size()), innerArrayBegin,
1421                                  innerArrayBegin + 1, pos))
1422                 .WillOnce(Return(&mpc));
1423         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[3])), pos, pos + 9, pos + 9))
1424                 .WillOnce(Return(&mpc));
1425         EXPECT_CALL(mpc, itemEnd(IsArrayOfSize(val.size()), encBegin, encBegin + 1, encEnd))
1426                 .WillOnce(Return(&mpc));
1427     }
1428 
1429     EXPECT_CALL(mpc, error(_, _))  //
1430             .Times(0);
1431 
1432     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1433 }
1434 
TEST(StreamParseTest,SemanticTag)1435 TEST(StreamParseTest, SemanticTag) {
1436     MockParseClient mpc;
1437     SemanticTag val(15, Array(-5, "Hi"));
1438     auto encoded = val.encode();
1439     ASSERT_NE(val.asArray(), nullptr);
1440     const Array& array = *(val.asArray());
1441     uint8_t* encBegin = encoded.data();
1442     uint8_t* encEnd = encoded.data() + encoded.size();
1443 
1444     {
1445         InSequence s;
1446         const uint8_t* pos = encBegin;
1447         EXPECT_CALL(mpc, item(IsSemanticTagOfValue(val.semanticTag()), pos, pos + 1, pos + 1))
1448                 .WillOnce(Return(&mpc));
1449         ++pos;
1450         const uint8_t* innerArrayBegin = pos;
1451         EXPECT_CALL(mpc, item(IsArrayOfSize(array.size()), pos, pos + 1, pos + 1))
1452                 .WillOnce(Return(&mpc));
1453         ++pos;
1454         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*array[0])), pos, pos + 1, pos + 1))
1455                 .WillOnce(Return(&mpc));
1456         ++pos;
1457         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*array[1])), pos, pos + 1, pos + 3))
1458                 .WillOnce(Return(&mpc));
1459         pos += 3;
1460         EXPECT_CALL(mpc,
1461                     itemEnd(IsArrayOfSize(array.size()), innerArrayBegin, innerArrayBegin + 1, pos))
1462                 .WillOnce(Return(&mpc));
1463         EXPECT_CALL(mpc, itemEnd(IsSemanticTagOfValue(val.semanticTag()), encBegin, encBegin + 1,
1464                                  encEnd))
1465                 .WillOnce(Return(&mpc));
1466     }
1467 
1468     EXPECT_CALL(mpc, error(_, _))  //
1469             .Times(0);
1470     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1471 }
1472 
TEST(StreamParseTest,Map)1473 TEST(StreamParseTest, Map) {
1474     MockParseClient mpc;
1475 
1476     Map val("Hello", 4, Array(-9, "Goodbye"), std::numeric_limits<uint64_t>::max());
1477     ASSERT_NE(val[1].first->asArray(), nullptr);
1478     const Array& interior = *(val[1].first->asArray());
1479     auto encoded = val.encode();
1480     uint8_t* encBegin = encoded.data();
1481     uint8_t* encEnd = encoded.data() + encoded.size();
1482 
1483     {
1484         InSequence s;
1485         const uint8_t* pos = encBegin;
1486         EXPECT_CALL(mpc, item(_, pos, pos + 1, pos + 1)).WillOnce(Return(&mpc));
1487         ++pos;
1488         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[0].first)), pos, pos + 1, pos + 6))
1489                 .WillOnce(Return(&mpc));
1490         pos += 6;
1491         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[0].second)), pos, pos + 1, pos + 1))
1492                 .WillOnce(Return(&mpc));
1493         ++pos;
1494         const uint8_t* innerArrayBegin = pos;
1495         EXPECT_CALL(mpc, item(IsArrayOfSize(interior.size()), pos, pos + 1, pos + 1))
1496                 .WillOnce(Return(&mpc));
1497         ++pos;
1498         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*interior[0])), pos, pos + 1, pos + 1))
1499                 .WillOnce(Return(&mpc));
1500         ++pos;
1501         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*interior[1])), pos, pos + 1, pos + 8))
1502                 .WillOnce(Return(&mpc));
1503         pos += 8;
1504         EXPECT_CALL(mpc, itemEnd(IsArrayOfSize(interior.size()), innerArrayBegin,
1505                                  innerArrayBegin + 1, pos))
1506                 .WillOnce(Return(&mpc));
1507         EXPECT_CALL(mpc, item(MatchesItem(ByRef(*val[1].second)), pos, pos + 9, pos + 9))
1508                 .WillOnce(Return(&mpc));
1509         EXPECT_CALL(mpc, itemEnd(IsMapOfSize(val.size()), encBegin, encBegin + 1, encEnd))
1510                 .WillOnce(Return(&mpc));
1511     }
1512 
1513     EXPECT_CALL(mpc, error(_, _))  //
1514             .Times(0);
1515 
1516     parse(encoded.data(), encoded.data() + encoded.size(), &mpc);
1517 }
1518 
TEST(StreamParseTest,ViewTstr)1519 TEST(StreamParseTest, ViewTstr) {
1520     MockParseClient mpc;
1521 
1522     ViewTstr val("Hello");
1523     auto encoded = val.encode();
1524     uint8_t* encBegin = encoded.data();
1525     uint8_t* encEnd = encoded.data() + encoded.size();
1526 
1527     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encBegin + 1, encEnd)).WillOnce(Return(&mpc));
1528     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1529     EXPECT_CALL(mpc, error(_, _)).Times(0);
1530 
1531     parseWithViews(encoded.data(), encoded.data() + encoded.size(), &mpc);
1532 }
1533 
TEST(StreamParseTest,ViewBstr)1534 TEST(StreamParseTest, ViewBstr) {
1535     MockParseClient mpc;
1536 
1537     ViewBstr val("Hello");
1538     auto encoded = val.encode();
1539     uint8_t* encBegin = encoded.data();
1540     uint8_t* encEnd = encoded.data() + encoded.size();
1541 
1542     EXPECT_CALL(mpc, item(MatchesItem(val), encBegin, encBegin + 1, encEnd)).WillOnce(Return(&mpc));
1543     EXPECT_CALL(mpc, itemEnd(_, _, _, _)).Times(0);
1544     EXPECT_CALL(mpc, error(_, _)).Times(0);
1545 
1546     parseWithViews(encoded.data(), encoded.data() + encoded.size(), &mpc);
1547 }
1548 
TEST(FullParserTest,Uint)1549 TEST(FullParserTest, Uint) {
1550     Uint val(10);
1551 
1552     auto [item, pos, message] = parse(val.encode());
1553     EXPECT_THAT(item, MatchesItem(val));
1554 }
1555 
TEST(FullParserTest,Null)1556 TEST(FullParserTest, Null) {
1557     Null val;
1558 
1559     auto [item, pos, message] = parse(val.encode());
1560     EXPECT_THAT(item, MatchesItem(val));
1561 }
1562 
TEST(FullParserTest,Nint)1563 TEST(FullParserTest, Nint) {
1564     Nint val(-10);
1565 
1566     auto [item, pos, message] = parse(val.encode());
1567     EXPECT_THAT(item, MatchesItem(val));
1568 
1569     vector<uint8_t> minNint = {0x3B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
1570 
1571     std::tie(item, pos, message) = parse(minNint);
1572     EXPECT_THAT(item, NotNull());
1573     EXPECT_EQ(item->asNint()->value(), std::numeric_limits<int64_t>::min());
1574 }
1575 
TEST(FullParserTest,NintOutOfRange)1576 TEST(FullParserTest, NintOutOfRange) {
1577     vector<uint8_t> outOfRangeNint = {0x3B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
1578 
1579     auto [item, pos, message] = parse(outOfRangeNint);
1580     EXPECT_THAT(item, IsNull());
1581     EXPECT_EQ(pos, outOfRangeNint.data());
1582     EXPECT_EQ(message, "NINT values that don't fit in int64_t are not supported.");
1583 }
1584 
TEST(FullParserTest,Tstr)1585 TEST(FullParserTest, Tstr) {
1586     Tstr val("Hello");
1587 
1588     auto [item, pos, message] = parse(val.encode());
1589     EXPECT_THAT(item, MatchesItem(val));
1590 }
1591 
TEST(FullParserTest,Bstr)1592 TEST(FullParserTest, Bstr) {
1593     Bstr val("\x00\x01\0x02"s);
1594 
1595     auto [item, pos, message] = parse(val.encode());
1596     EXPECT_THAT(item, MatchesItem(val));
1597 }
1598 
TEST(FullParserTest,Array)1599 TEST(FullParserTest, Array) {
1600     Array val("hello", -4, 3);
1601 
1602     auto encoded = val.encode();
1603     auto [item, pos, message] = parse(encoded);
1604     EXPECT_THAT(item, MatchesItem(ByRef(val)));
1605     EXPECT_EQ(pos, encoded.data() + encoded.size());
1606     EXPECT_EQ("", message);
1607 
1608     // We've already checked it all, but walk it just for fun.
1609     ASSERT_NE(nullptr, item->asArray());
1610     const Array& arr = *(item->asArray());
1611     ASSERT_EQ(arr[0]->type(), TSTR);
1612     EXPECT_EQ(arr[0]->asTstr()->value(), "hello");
1613 }
1614 
TEST(FullParserTest,Map)1615 TEST(FullParserTest, Map) {
1616     Map val("hello", -4, 3, Bstr("hi"));
1617 
1618     auto [item, pos, message] = parse(val.encode());
1619     EXPECT_THAT(item, MatchesItem(ByRef(val)));
1620 }
1621 
TEST(FullParserTest,SemanticTag)1622 TEST(FullParserTest, SemanticTag) {
1623     SemanticTag val(99, "Salem");
1624 
1625     auto [item, pos, message] = parse(val.encode());
1626     EXPECT_THAT(item, MatchesItem(ByRef(val)));
1627 }
1628 
TEST(FullParserTest,NestedSemanticTag)1629 TEST(FullParserTest, NestedSemanticTag) {
1630     SemanticTag val(10, SemanticTag(99, "Salem"));
1631 
1632     auto [item, pos, message] = parse(val.encode());
1633     EXPECT_THAT(item, MatchesItem(ByRef(val)));
1634 }
1635 
TEST(FullParserTest,Complex)1636 TEST(FullParserTest, Complex) {
1637     vector<uint8_t> vec = {0x01, 0x02, 0x08, 0x03};
1638     Map val("Outer1",
1639             Array(Map("Inner1", 99,  //
1640                       "Inner2", vec),
1641                   "foo"),
1642             "Outer2", 10);
1643 
1644     std::unique_ptr<Item> item;
1645     const uint8_t* pos;
1646     std::string message;
1647     std::tie(item, pos, message) = parse(val.encode());
1648     EXPECT_THAT(item, MatchesItem(ByRef(val)));
1649 }
1650 
TEST(FullParserTest,IncompleteUint)1651 TEST(FullParserTest, IncompleteUint) {
1652     Uint val(1000);
1653 
1654     auto encoding = val.encode();
1655     auto [item, pos, message] = parse(encoding.data(), encoding.size() - 1);
1656     EXPECT_EQ(nullptr, item.get());
1657     EXPECT_EQ(encoding.data(), pos);
1658     EXPECT_EQ("Need 2 byte(s) for length field, have 1.", message);
1659 }
1660 
TEST(FullParserTest,IncompleteString)1661 TEST(FullParserTest, IncompleteString) {
1662     Tstr val("hello");
1663 
1664     auto encoding = val.encode();
1665     auto [item, pos, message] = parse(encoding.data(), encoding.size() - 2);
1666     EXPECT_EQ(nullptr, item.get());
1667     EXPECT_EQ(encoding.data(), pos);
1668     EXPECT_EQ("Need 5 byte(s) for text string, have 3.", message);
1669 }
1670 
TEST(FullParserTest,ArrayWithInsufficientEntries)1671 TEST(FullParserTest, ArrayWithInsufficientEntries) {
1672     Array val(1, 2, 3, 4);
1673 
1674     auto encoding = val.encode();
1675     auto [item, pos, message] = parse(encoding.data(), encoding.size() - 1);
1676     EXPECT_EQ(nullptr, item.get());
1677     EXPECT_EQ(encoding.data(), pos);
1678     EXPECT_EQ("Not enough entries for array.", message);
1679 }
1680 
TEST(FullParserTest,ArrayWithTruncatedEntry)1681 TEST(FullParserTest, ArrayWithTruncatedEntry) {
1682     Array val(1, 2, 3, 400000);
1683 
1684     auto encoding = val.encode();
1685     auto [item, pos, message] = parse(encoding.data(), encoding.size() - 1);
1686     EXPECT_EQ(nullptr, item.get());
1687     EXPECT_EQ(encoding.data() + encoding.size() - 5, pos);
1688     EXPECT_EQ("Need 4 byte(s) for length field, have 3.", message);
1689 }
1690 
TEST(FullParserTest,MapWithTruncatedEntry)1691 TEST(FullParserTest, MapWithTruncatedEntry) {
1692     Map val(1, 2, 300000, 4);
1693 
1694     auto encoding = val.encode();
1695     auto [item, pos, message] = parse(encoding.data(), encoding.size() - 2);
1696     EXPECT_EQ(nullptr, item.get());
1697     EXPECT_EQ(encoding.data() + 3, pos);
1698     EXPECT_EQ("Need 4 byte(s) for length field, have 3.", message);
1699 }
1700 
TEST(FullParserTest,ViewTstr)1701 TEST(FullParserTest, ViewTstr) {
1702     ViewTstr val("Hello");
1703 
1704     auto enc = val.encode();
1705     auto [item, pos, message] = parseWithViews(enc.data(), enc.size());
1706     EXPECT_THAT(item, MatchesItem(val));
1707 }
1708 
TEST(FullParserTest,ViewBstr)1709 TEST(FullParserTest, ViewBstr) {
1710     ViewBstr val("\x00\x01\x02"s);
1711 
1712     auto enc = val.encode();
1713     auto [item, pos, message] = parseWithViews(enc.data(), enc.size());
1714     EXPECT_THAT(item, MatchesItem(val));
1715 }
1716 
TEST(FullParserTest,ReservedAdditionalInformation)1717 TEST(FullParserTest, ReservedAdditionalInformation) {
1718     vector<uint8_t> reservedVal = {0x1D};
1719 
1720     auto [item, pos, message] = parse(reservedVal);
1721     EXPECT_THAT(item, IsNull());
1722     EXPECT_EQ(pos, reservedVal.data());
1723     EXPECT_EQ("Reserved additional information value or unsupported indefinite length item.",
1724               message);
1725 }
1726 
TEST(FullParserTest,IndefiniteArray)1727 TEST(FullParserTest, IndefiniteArray) {
1728     vector<uint8_t> indefiniteArray = {0x7F};
1729 
1730     auto [item, pos, message] = parse(indefiniteArray);
1731     EXPECT_THAT(item, IsNull());
1732     EXPECT_EQ(pos, indefiniteArray.data());
1733     EXPECT_EQ("Reserved additional information value or unsupported indefinite length item.",
1734               message);
1735 }
1736 
TEST(FullParserTest,UnassignedSimpleValue)1737 TEST(FullParserTest, UnassignedSimpleValue) {
1738     vector<uint8_t> unassignedSimpleValue = {0xE5};
1739 
1740     auto [item, pos, message] = parse(unassignedSimpleValue);
1741     EXPECT_THAT(item, IsNull());
1742     EXPECT_EQ(pos, unassignedSimpleValue.data());
1743     EXPECT_EQ("Unsupported floating-point or simple value.", message);
1744 }
1745 
TEST(FullParserTest,FloatingPointValue)1746 TEST(FullParserTest, FloatingPointValue) {
1747     vector<uint8_t> floatingPointValue = {0xFA, 0x12, 0x75, 0x34, 0x37};
1748 
1749     auto [item, pos, message] = parse(floatingPointValue);
1750     EXPECT_THAT(item, IsNull());
1751     EXPECT_EQ(pos, floatingPointValue.data());
1752     EXPECT_EQ("Unsupported floating-point or simple value.", message);
1753 }
1754 
TEST(MapGetValueByKeyTest,Map)1755 TEST(MapGetValueByKeyTest, Map) {
1756     Array compoundItem(1, 2, 3, 4, 5, Map(4, 5, "a", "b"));
1757     auto clone = compoundItem.clone();
1758     Map item(1, 2, "key", "value", "item", std::move(compoundItem));
1759     auto& value1 = item.get(1);
1760     EXPECT_NE(value1.get(), nullptr);
1761     EXPECT_EQ(*value1, Uint(2));
1762     auto& value2 = item.get("key");
1763     EXPECT_NE(value2.get(), nullptr);
1764     EXPECT_EQ(*value2, Tstr("value"));
1765     auto& value3 = item.get("item");
1766     EXPECT_NE(value3.get(), nullptr);
1767     EXPECT_EQ(*value3, *clone);
1768     auto& value4 = item.get("wrong");
1769     EXPECT_EQ(value4.get(), nullptr);
1770 }
1771 
TEST(EmptyBstrTest,Bstr)1772 TEST(EmptyBstrTest, Bstr) {
1773     Bstr bstr(std::vector<uint8_t>{});
1774     auto encoding = bstr.encode();
1775     auto [obj, pos, message] = parse(encoding.data(), encoding.size());
1776     EXPECT_NE(obj.get(), nullptr);
1777     EXPECT_EQ(*obj, bstr);
1778 }
1779 
TEST(ArrayIterationTest,EmptyArray)1780 TEST(ArrayIterationTest, EmptyArray) {
1781     Array array;
1782     EXPECT_EQ(array.begin(), array.end());
1783 
1784     const Array& const_array = array;
1785     EXPECT_EQ(const_array.begin(), const_array.end());
1786 }
1787 
TEST(ArrayIterationTest,ForwardTest)1788 TEST(ArrayIterationTest, ForwardTest) {
1789     Array array(1, 2, 3, "hello", -4);
1790 
1791     auto iter = array.begin();
1792     ASSERT_NE(iter, array.end());
1793     EXPECT_EQ(**iter, Uint(1));
1794 
1795     ASSERT_NE(++iter, array.end());
1796     EXPECT_EQ(**iter++, Uint(2));
1797 
1798     ASSERT_NE(iter, array.end());
1799     EXPECT_EQ(**iter, Uint(3));
1800 
1801     ASSERT_NE(++iter, array.end());
1802     EXPECT_EQ(**iter++, Tstr("hello"));
1803 
1804     ASSERT_NE(iter, array.end());
1805     EXPECT_EQ(**iter, Nint(-4));
1806 
1807     EXPECT_EQ(++iter, array.end());
1808 }
1809 
TEST(ArrayIterationTest,BidirectionalTest)1810 TEST(ArrayIterationTest, BidirectionalTest) {
1811     Array array(1, 2, 3, "hello", -4);
1812 
1813     auto iter = array.begin();
1814     ASSERT_NE(iter, array.end());
1815     EXPECT_EQ(**iter, Uint(1));
1816 
1817     ASSERT_NE(++iter, array.end());
1818     EXPECT_EQ(**iter, Uint(2));
1819 
1820     ASSERT_NE(--iter, array.end());
1821     ASSERT_EQ(iter, array.begin());
1822     EXPECT_EQ(**iter, Uint(1));
1823 
1824     ASSERT_NE(++iter, array.end());
1825     EXPECT_EQ(**iter, Uint(2));
1826 
1827     ASSERT_NE(++iter, array.end());
1828     EXPECT_EQ(**iter--, Uint(3));
1829 
1830     ASSERT_NE(++iter, array.end());
1831     EXPECT_EQ(**iter, Uint(3));
1832 
1833     ASSERT_NE(++iter, array.end());
1834     EXPECT_EQ(**iter, Tstr("hello"));
1835 
1836     ASSERT_NE(++iter, array.end());
1837     EXPECT_EQ(**iter, Nint(-4));
1838 
1839     EXPECT_EQ(++iter, array.end());
1840 }
1841 
TEST(MapIterationTest,EmptyMap)1842 TEST(MapIterationTest, EmptyMap) {
1843     Map map;
1844 
1845     EXPECT_EQ(map.begin(), map.end());
1846 }
1847 
TEST(MapIterationTest,ForwardTest)1848 TEST(MapIterationTest, ForwardTest) {
1849     Map map(1, 2, 3, "hello", -4, 5);
1850 
1851     auto iter = map.begin();
1852     ASSERT_NE(iter, map.end());
1853     EXPECT_EQ(*iter->first, Uint(1));
1854     EXPECT_EQ(*iter->second, Uint(2));
1855 
1856     ASSERT_NE(++iter, map.end());
1857     EXPECT_EQ(*iter->first, Uint(3));
1858     EXPECT_EQ(*(iter++)->second, Tstr("hello"));
1859 
1860     ASSERT_NE(iter, map.end());
1861     EXPECT_EQ(*iter->first, Nint(-4));
1862     EXPECT_EQ(*(iter++)->second, Uint(5));
1863 
1864     EXPECT_EQ(iter, map.end());
1865 }
1866 
TEST(MapIterationTest,BidirectionalTest)1867 TEST(MapIterationTest, BidirectionalTest) {
1868     Map map(1, 2, 3, "hello", -4, 5);
1869 
1870     auto iter = map.begin();
1871     ASSERT_NE(iter, map.end());
1872     EXPECT_EQ(*iter->first, Uint(1));
1873     EXPECT_EQ(*iter->second, Uint(2));
1874 
1875     ASSERT_NE(++iter, map.end());
1876     EXPECT_EQ(*iter->first, Uint(3));
1877     EXPECT_EQ(*(iter--)->second, Tstr("hello"));
1878 
1879     ASSERT_NE(iter, map.end());
1880     EXPECT_EQ(*iter->first, Uint(1));
1881     EXPECT_EQ(*(iter++)->second, Uint(2));
1882 
1883     ASSERT_NE(iter, map.end());
1884     EXPECT_EQ(*iter->first, Uint(3));
1885     EXPECT_EQ(*iter->second, Tstr("hello"));
1886 
1887     ASSERT_NE(++iter, map.end());
1888     EXPECT_EQ(*iter->first, Nint(-4));
1889     EXPECT_EQ(*(iter++)->second, Uint(5));
1890 
1891     EXPECT_EQ(iter, map.end());
1892 }
1893 
main(int argc,char ** argv)1894 int main(int argc, char** argv) {
1895     ::testing::InitGoogleTest(&argc, argv);
1896     return RUN_ALL_TESTS();
1897 }
1898