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
6
7#include <cstdarg>
8#include <vector>
9#include <string>
10
11#ifdef LOGIT_USE_FMT_LIB
12#include <fmt/core.h>
13#endif
14
15namespace logit {
16
27 inline std::string format(const char *fmt, ...) {
28# ifdef LOGIT_USE_FMT_LIB
29 va_list args;
30 va_start(args, fmt);
31 std::string result = fmt::vformat(fmt, fmt::make_format_args(args));
32 va_end(args);
33 return result;
34# else
35 va_list args;
36 va_start(args, fmt);
37 std::vector<char> buffer(1024);
38 for (;;) {
39 va_list args_copy;
40 va_copy(args_copy, args); // Copy args to prevent modifying the original list.
41 int res = vsnprintf(buffer.data(), buffer.size(), fmt, args_copy);
42 va_end(args_copy); // Clean up the copied argument list.
43
44 if ((res >= 0) && (res < static_cast<int>(buffer.size()))) {
45 va_end(args); // Clean up the original argument list.
46 return std::string(buffer.data()); // Return the formatted string.
47 }
48
49 // If the buffer was too small, resize it.
50 const size_t size = res < 0 ? buffer.size() * 2 : static_cast<size_t>(res) + 1;
51 buffer.clear();
52 buffer.resize(size);
53 }
54# endif
55 }
56
57# ifndef LOGIT_USE_FMT_LIB
67 inline std::string format(const std::string& fmt, ...) {
68 va_list args;
69 va_start(args, fmt);
70 std::vector<char> buffer(1024);
71 for (;;) {
72 va_list args_copy;
73 va_copy(args_copy, args); // Copy args to prevent modifying the original list.
74 int res = vsnprintf(buffer.data(), buffer.size(), fmt.c_str(), args_copy);
75 va_end(args_copy); // Clean up the copied argument list.
76
77 if ((res >= 0) && (res < static_cast<int>(buffer.size()))) {
78 va_end(args); // Clean up the original argument list.
79 return std::string(buffer.data()); // Return the formatted string.
80 }
81
82 // If the buffer was too small, resize it.
83 const size_t size = res < 0 ? buffer.size() * 2 : static_cast<size_t>(res) + 1;
84 buffer.clear();
85 buffer.resize(size);
86 }
87 }
88# else
95 inline std::string format_string(const std::string& fmt) {
96 return fmt;
97 }
98
107 template <typename... Args>
108 inline std::string format_string(const std::string& fmt, Args&&... args) {
109 return fmt::format(fmt, std::forward<Args>(args)...);
110 }
111# endif
112
113}; // namespace logit
114
115#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:27