Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / support / BytesToHex.cpp
1 /*
2  *
3  *    Copyright (c) 2021 Project CHIP Authors
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 "BytesToHex.h"
19
20 namespace chip {
21 namespace Encoding {
22
23 namespace {
24
25 char NibbleToHex(uint8_t nibble, bool uppercase)
26 {
27     char x = static_cast<char>(nibble & 0xFu);
28
29     if (x >= 10)
30     {
31         return static_cast<char>((x - 10) + (uppercase ? 'A' : 'a'));
32     }
33     else
34     {
35         return static_cast<char>(x + '0');
36     }
37 }
38
39 } // namespace
40
41 CHIP_ERROR BytesToHex(const uint8_t * src_bytes, size_t src_size, char * dest_hex, size_t dest_size_max, BitFlags<HexFlags> flags)
42 {
43     if ((src_bytes == nullptr) || (dest_hex == nullptr))
44     {
45         return CHIP_ERROR_INVALID_ARGUMENT;
46     }
47     else if (src_size > ((SIZE_MAX - 1) / 2u))
48     {
49         // Output would overflow a size_t, let's bail out to avoid computation wraparounds below.
50         // This condition will hit with slightly less than the very max, but is unlikely to
51         // ever happen unless an error occurs and won't happen on embedded targets.
52         return CHIP_ERROR_INVALID_ARGUMENT;
53     }
54
55     bool nul_terminate          = flags.Has(HexFlags::kNullTerminate);
56     size_t expected_output_size = (src_size * 2u) + (nul_terminate ? 1u : 0u);
57     if (dest_size_max < expected_output_size)
58     {
59         return CHIP_ERROR_BUFFER_TOO_SMALL;
60     }
61
62     bool uppercase = flags.Has(HexFlags::kUppercase);
63     char * cursor  = dest_hex;
64     for (size_t byte_idx = 0; byte_idx < src_size; ++byte_idx)
65     {
66         *cursor++ = NibbleToHex((src_bytes[byte_idx] >> 4) & 0xFu, uppercase);
67         *cursor++ = NibbleToHex((src_bytes[byte_idx] >> 0) & 0xFu, uppercase);
68     }
69
70     if (nul_terminate)
71     {
72         *cursor = '\0';
73     }
74
75     return CHIP_NO_ERROR;
76 }
77
78 } // namespace Encoding
79 } // namespace chip