Container System 0.1.0
High-performance C++20 type-safe container framework with SIMD-accelerated serialization
Loading...
Searching...
No Matches
formatter.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2021-2025, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
5#pragma once
6
7#include <string>
8
9#if __has_include(<format>)
10#include <format>
11#endif
12
13#if defined(__cpp_lib_format) && __cpp_lib_format >= 202110L
14#define UTILITY_MODULE_HAS_STD_FORMAT 1
15#else
16#define UTILITY_MODULE_HAS_STD_FORMAT 0
17#include <sstream>
18#endif
19
20namespace utility_module {
21
29class formatter {
30public:
31#if UTILITY_MODULE_HAS_STD_FORMAT
32
33 template<typename... Args>
34 static std::string format(const std::string& format_str, Args&&... args) {
35 try {
36 return std::vformat(format_str, std::make_format_args(args...));
37 } catch (const std::exception&) {
38 return format_str; // Return original string if formatting fails
39 }
40 }
41
42 template<typename OutputIt, typename... Args>
43 static void format_to(OutputIt out, const std::string& format_str, Args&&... args) {
44 try {
45 std::vformat_to(out, format_str, std::make_format_args(args...));
46 } catch (const std::exception&) {
47 // Fallback: just copy the format string
48 std::copy(format_str.begin(), format_str.end(), out);
49 }
50 }
51
52#else // fallback: ostringstream-based {} substitution
53
54 template<typename... Args>
55 static std::string format(const std::string& format_str, Args&&... args) {
56 std::string result = format_str;
57 (replace_next(result, std::forward<Args>(args)), ...);
58 return result;
59 }
60
61 template<typename OutputIt, typename... Args>
62 static void format_to(OutputIt out, const std::string& format_str, Args&&... args) {
63 std::string result = format(format_str, std::forward<Args>(args)...);
64 std::copy(result.begin(), result.end(), out);
65 }
66
67#endif
68
69 static std::string format(const std::string& format_str) {
70 return format_str;
71 }
72
73private:
74#if !UTILITY_MODULE_HAS_STD_FORMAT
75 template<typename T>
76 static void replace_next(std::string& str, T&& value) {
77 auto pos = str.find("{}");
78 if (pos == std::string::npos) return;
79
80 std::ostringstream oss;
81 oss << std::forward<T>(value);
82 str.replace(pos, 2, oss.str());
83 }
84#endif
85};
86
87} // namespace utility_module
Simple formatter wrapper around std::format.
Definition formatter.h:29
static void format_to(OutputIt out, const std::string &format_str, Args &&... args)
Definition formatter.h:62
static std::string format(const std::string &format_str, Args &&... args)
Definition formatter.h:55
static std::string format(const std::string &format_str)
Definition formatter.h:69
static void replace_next(std::string &str, T &&value)
Definition formatter.h:76