blob: 49c29dc8ee0e12e84f8bdad26f438de6ea196047 [file] [log] [blame]
Yuri Wiitalacb9bf582020-02-11 16:29:15 -08001// 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 Wiitala2837c9f2020-10-26 12:30:13 -07007#include <cstdarg>
8#include <cstdio>
Yuri Wiitalacb9bf582020-02-11 16:29:15 -08009#include <iomanip>
10#include <sstream>
11
Yuri Wiitala2837c9f2020-10-26 12:30:13 -070012#include "util/osp_logging.h"
13
Yuri Wiitalacb9bf582020-02-11 16:29:15 -080014namespace openscreen {
15
Yuri Wiitala2837c9f2020-10-26 12:30:13 -070016std::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 Gumbs7e167e22021-07-07 15:54:14 -040035std::string HexEncode(const uint8_t* bytes, std::size_t len) {
Yuri Wiitalacb9bf582020-02-11 16:29:15 -080036 std::ostringstream hex_dump;
37 hex_dump << std::setfill('0') << std::hex;
Kennan Gumbs7e167e22021-07-07 15:54:14 -040038 for (std::size_t i = 0; i < len; i++) {
39 hex_dump << std::setw(2) << static_cast<int>(bytes[i]);
Yuri Wiitalacb9bf582020-02-11 16:29:15 -080040 }
41 return hex_dump.str();
42}
43
44} // namespace openscreen