1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "util/stringprintf.h"
6 
7 #include <cstdarg>
8 #include <cstdio>
9 #include <iomanip>
10 #include <sstream>
11 
12 #include "util/osp_logging.h"
13 
14 namespace openscreen {
15 
StringPrintf(const char * format,...)16 std::string StringPrintf(const char* format, ...) {
17   va_list vlist;
18   va_start(vlist, format);
19   const int length = std::vsnprintf(nullptr, 0, format, vlist);
20   OSP_CHECK_GE(length, 0) << "Invalid format string: " << format;
21   va_end(vlist);
22 
23   std::string result(length, '\0');
24   // Note: There's no need to add one for the extra terminating NUL char since
25   // the standard, since C++11, requires that "data() + size() points to [the
26   // NUL terminator]". Thus, std::vsnprintf() will write the NUL to a valid
27   // memory location.
28   va_start(vlist, format);
29   std::vsnprintf(&result[0], length + 1, format, vlist);
30   va_end(vlist);
31 
32   return result;
33 }
34 
HexEncode(absl::Span<const uint8_t> bytes)35 std::string HexEncode(absl::Span<const uint8_t> bytes) {
36   std::ostringstream hex_dump;
37   hex_dump << std::setfill('0') << std::hex;
38   for (const uint8_t byte : bytes) {
39     hex_dump << std::setw(2) << static_cast<int>(byte);
40   }
41   return hex_dump.str();
42 }
43 
44 }  // namespace openscreen
45