LogIt++
Header-only, macro-first C++ logging library
Loading...
Searching...
No Matches
format.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_FORMAT_HPP_INCLUDED
3#define LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_FORMAT_HPP_INCLUDED
4
7
8#include <cstdarg>
9#include <vector>
10#include <string>
11
12namespace logit {
13
22 inline std::string format(const char *fmt, ...) {
23 va_list args;
24 va_start(args, fmt);
25 std::vector<char> buffer(1024);
26 for (;;) {
27 va_list args_copy;
28 va_copy(args_copy, args); // Copy args to prevent modifying the original list.
29 int res = vsnprintf(buffer.data(), buffer.size(), fmt, args_copy);
30 va_end(args_copy); // Clean up the copied argument list.
31
32 if ((res >= 0) && (res < static_cast<int>(buffer.size()))) {
33 va_end(args); // Clean up the original argument list.
34 return std::string(buffer.data()); // Return the formatted string.
35 }
36
37 // If the buffer was too small, resize it.
38 const size_t size = res < 0 ? buffer.size() * 2 : static_cast<size_t>(res) + 1;
39 buffer.clear();
40 buffer.resize(size);
41 }
42 }
43
44}; // namespace logit
45
46#endif // LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_FORMAT_HPP_INCLUDED
The primary namespace for the LogIt++ library.
std::string format(const char *fmt,...)
Formats a string according to the specified format.
Definition format.hpp:22