LogIt++
Loading...
Searching...
No Matches
format.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _LOGIT_FORMAT_HPP_INCLUDED
3#define _LOGIT_FORMAT_HPP_INCLUDED
4
7
8#include <cstdarg>
9#include <vector>
10#include <string>
11
12#ifdef LOGIT_USE_FMT_LIB
13#include <fmt/core.h>
14#endif
15
16namespace logit {
17
28 inline std::string format(const char *fmt, ...) {
29# ifdef LOGIT_USE_FMT_LIB
30 va_list args;
31 va_start(args, fmt);
32 std::string result = fmt::vformat(fmt, fmt::make_format_args(args));
33 va_end(args);
34 return result;
35# else
36 va_list args;
37 va_start(args, fmt);
38 std::vector<char> buffer(1024);
39 for (;;) {
40 va_list args_copy;
41 va_copy(args_copy, args); // Copy args to prevent modifying the original list.
42 int res = vsnprintf(buffer.data(), buffer.size(), fmt, args_copy);
43 va_end(args_copy); // Clean up the copied argument list.
44
45 if ((res >= 0) && (res < static_cast<int>(buffer.size()))) {
46 va_end(args); // Clean up the original argument list.
47 return std::string(buffer.data()); // Return the formatted string.
48 }
49
50 // If the buffer was too small, resize it.
51 const size_t size = res < 0 ? buffer.size() * 2 : static_cast<size_t>(res) + 1;
52 buffer.clear();
53 buffer.resize(size);
54 }
55# endif
56 }
57
58}; // namespace logit
59
60#endif // _LOGIT_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:28