Yuri Wiitala | cb9bf58 | 2020-02-11 16:29:15 -0800 | [diff] [blame] | 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 | |
Yuri Wiitala | 2837c9f | 2020-10-26 12:30:13 -0700 | [diff] [blame] | 7 | #include <cstdarg> |
| 8 | #include <cstdio> |
Yuri Wiitala | cb9bf58 | 2020-02-11 16:29:15 -0800 | [diff] [blame] | 9 | #include <iomanip> |
| 10 | #include <sstream> |
| 11 | |
Yuri Wiitala | 2837c9f | 2020-10-26 12:30:13 -0700 | [diff] [blame] | 12 | #include "util/osp_logging.h" |
| 13 | |
Yuri Wiitala | cb9bf58 | 2020-02-11 16:29:15 -0800 | [diff] [blame] | 14 | namespace openscreen { |
| 15 | |
Yuri Wiitala | 2837c9f | 2020-10-26 12:30:13 -0700 | [diff] [blame] | 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 | |
Kennan Gumbs | 7e167e2 | 2021-07-07 15:54:14 -0400 | [diff] [blame] | 35 | std::string HexEncode(const uint8_t* bytes, std::size_t len) { |
Yuri Wiitala | cb9bf58 | 2020-02-11 16:29:15 -0800 | [diff] [blame] | 36 | std::ostringstream hex_dump; |
| 37 | hex_dump << std::setfill('0') << std::hex; |
Kennan Gumbs | 7e167e2 | 2021-07-07 15:54:14 -0400 | [diff] [blame] | 38 | for (std::size_t i = 0; i < len; i++) { |
| 39 | hex_dump << std::setw(2) << static_cast<int>(bytes[i]); |
Yuri Wiitala | cb9bf58 | 2020-02-11 16:29:15 -0800 | [diff] [blame] | 40 | } |
| 41 | return hex_dump.str(); |
| 42 | } |
| 43 | |
| 44 | } // namespace openscreen |