1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  *     Copyright 2017 Couchbase, Inc.
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License");
6  *   you may not use this file except in compliance with the License.
7  *   You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS,
13  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *   See the License for the specific language governing permissions and
15  *   limitations under the License.
16  */
17 
18 #include <folly/portability/GTest.h>
19 #include <platform/string_hex.h>
20 
TEST(Hex, InputStringTooLong)21 TEST(Hex, InputStringTooLong) {
22     std::stringstream ss;
23     ss << std::hex << uint64_t(-1);
24     EXPECT_EQ(-1ULL, cb::from_hex(ss.str()));
25     // Make sure it won't fit in there
26     ss << "0";
27     EXPECT_THROW(cb::from_hex(ss.str()), std::overflow_error);
28 }
29 
TEST(Hex, InputStringData)30 TEST(Hex, InputStringData) {
31     const std::string value{"0123456789abcdef"};
32     const uint64_t expected{0x0123456789abcdefULL};
33     EXPECT_EQ(expected, cb::from_hex(value));
34 }
35 
TEST(Hex, ToHexUint8)36 TEST(Hex, ToHexUint8) {
37     uint8_t val = uint8_t(-1);
38     EXPECT_EQ("0xff", cb::to_hex(val));
39     val = 0;
40     EXPECT_EQ("0x00", cb::to_hex(val));
41 }
42 
TEST(Hex, ToHexUint16)43 TEST(Hex, ToHexUint16) {
44     uint16_t val = uint16_t(-1);
45     EXPECT_EQ("0xffff", cb::to_hex(val));
46     val = 0;
47     EXPECT_EQ("0x0000", cb::to_hex(val));
48 }
49 
TEST(Hex, ToHexUint32)50 TEST(Hex, ToHexUint32) {
51     uint32_t val = uint32_t(-1);
52     EXPECT_EQ("0xffffffff", cb::to_hex(val));
53     val = 0;
54     EXPECT_EQ("0x00000000", cb::to_hex(val));
55 }
56 
TEST(Hex, ToHexUint64)57 TEST(Hex, ToHexUint64) {
58     uint64_t val = uint64_t(-1);
59     EXPECT_EQ("0xffffffffffffffff", cb::to_hex(val));
60     val = 0;
61     EXPECT_EQ("0x0000000000000000", cb::to_hex(val));
62 }
63 
TEST(Hex, ToHexByteBuffer)64 TEST(Hex, ToHexByteBuffer) {
65     std::vector<uint8_t> buffer(4);
66     for (auto& c : buffer) {
67         c = 0xa5;
68     }
69     EXPECT_EQ("0xa5 0xa5 0xa5 0xa5",
70               cb::to_hex({buffer.data(), buffer.size()}));
71 }
72