11#pragma once
22
3- // This component provides a function, `hex`, for formatting an integral value
3+ // This component provides functions for formatting an unsigned integral value
44// in hexadecimal.
55
66#include < cassert>
1212namespace datadog {
1313namespace tracing {
1414
15- // Return the specified `value` formatted as a lower-case hexadecimal string
16- // without any leading zeroes.
17- template <typename Integer>
18- std::string hex (Integer value) {
19- // 4 bits per hex digit char, and then +1 char for possible minus sign
20- char buffer[std::numeric_limits<Integer>::digits / 4 + 1 ];
15+ // Return the specified unsigned `value` formatted as a lower-case hexadecimal
16+ // string without any leading zeroes.
17+ template <typename UnsignedInteger>
18+ std::string hex (UnsignedInteger value) {
19+ static_assert (!std::numeric_limits<UnsignedInteger>::is_signed);
20+
21+ // 4 bits per hex digit char
22+ char buffer[std::numeric_limits<UnsignedInteger>::digits / 4 ];
2123
2224 const int base = 16 ;
2325 auto result =
@@ -27,5 +29,25 @@ std::string hex(Integer value) {
2729 return std::string{std::begin (buffer), result.ptr };
2830}
2931
32+ // Return the specified unsigned `value` formatted as a lower-case hexadecimal
33+ // string with leading zeroes.
34+ template <typename UnsignedInteger>
35+ std::string hex_padded (UnsignedInteger value) {
36+ static_assert (!std::numeric_limits<UnsignedInteger>::is_signed);
37+
38+ // 4 bits per hex digit char.
39+ char buffer[std::numeric_limits<UnsignedInteger>::digits / 4 ];
40+
41+ const int base = 16 ;
42+ auto result =
43+ std::to_chars (std::begin (buffer), std::end (buffer), value, base);
44+ assert (result.ec == std::errc ());
45+
46+ const auto num_zeroes = sizeof (buffer) - (result.ptr - std::begin (buffer));
47+ std::string padded (num_zeroes, ' 0' );
48+ padded.append (std::begin (buffer), result.ptr );
49+ return padded;
50+ }
51+
3052} // namespace tracing
3153} // namespace datadog
0 commit comments