Software APIs
hexstr_unittest.cc
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 #include "sw/device/lib/testing/hexstr.h"
6 
7 #include <stdint.h>
8 
9 #include "gmock/gmock.h"
10 #include "gtest/gtest.h"
11 
12 namespace {
13 
14 TEST(HexStr, Encode) {
15  uint32_t value = 0x01020304;
16  char buf[9];
17 
18  status_t result = hexstr_encode(buf, sizeof(buf), &value, sizeof(value));
19  EXPECT_TRUE(status_ok(result));
20  EXPECT_EQ(std::string(buf), "04030201");
21 }
22 
23 TEST(HexStr, EncodeShortBuf) {
24  uint32_t value = 0x01020304;
25  // Buf is too short - it omits space for the nul terminator.
26  char buf[8];
27 
28  status_t result = hexstr_encode(buf, sizeof(buf), &value, sizeof(value));
29  EXPECT_FALSE(status_ok(result));
30 }
31 
32 TEST(HexStr, Decode) {
33  char str[] = "11223344";
34  uint32_t value = 0;
35 
36  status_t result = hexstr_decode(&value, sizeof(value), str);
37  EXPECT_TRUE(status_ok(result));
38  EXPECT_EQ(value, 0x44332211);
39 }
40 
41 TEST(HexStr, DecodeShortBuf) {
42  char str[] = "1122334455667788";
43  // 32-bit int is too small to hold the decoded value.
44  uint32_t value = 0;
45 
46  status_t result = hexstr_decode(&value, sizeof(value), str);
47  EXPECT_FALSE(status_ok(result));
48 }
49 
50 TEST(HexStr, DecodeShortInput) {
51  // The input is an odd length.
52  char str[] = "1122334";
53  uint32_t value = 0;
54 
55  status_t result = hexstr_decode(&value, sizeof(value), str);
56  EXPECT_FALSE(status_ok(result));
57 }
58 
59 TEST(HexStr, DecodeIllegalInput) {
60  // The contains in invalid character.
61  char str[] = "1122334x";
62  uint32_t value = 0;
63 
64  status_t result = hexstr_decode(&value, sizeof(value), str);
65  EXPECT_FALSE(status_ok(result));
66 }
67 
68 } // namespace