arduino-audio-tools
Loading...
Searching...
No Matches
Format.h
Go to the documentation of this file.
1
2#pragma once
3
4#if __cplusplus >= 202002L
5// C++20 or newer is supported
6#include <format>
7#else
8
9#include "Str.h"
10namespace std {
11
20class Format {
21 public:
22 template <typename... Args>
23 Format(const char* fmt, Args... args) {
24 parse(fmt, args...);
25 }
26
28 const char* c_str() { return buffer_.c_str(); }
29
31 operator const char*() { return buffer_.c_str(); }
32
33 private:
34 audio_tools::Str buffer_;
35
36 // Base case: process remaining format string when arguments run out
37 void parse(const char* fmt) {
38 while (*fmt != '\0') {
39 // Check for escaped '{{' or '}}'
40 if (*fmt == '{' && *(fmt + 1) == '{') {
41 buffer_ += '{';
42 fmt += 2;
43 continue;
44 }
45 if (*fmt == '}' && *(fmt + 1) == '}') {
46 buffer_ += '}';
47 fmt += 2;
48 continue;
49 }
50 buffer_ += *fmt++;
51 }
52 }
53
54 // Recursive variadic template worker
55 template <typename T, typename... Args>
56 void parse(const char* fmt, T head_value, Args... tail_args) {
57 while (*fmt != '\0') {
58 // Check for '{}' placeholder
59 if (*fmt == '{' && *(fmt + 1) == '}') {
60 buffer_ += head_value; // Append parameter
61 parse(fmt + 2, tail_args...); // Recurse onto remaining arguments
62 return;
63 }
64 // Check for escaped '{{' or '}}'
65 if (*fmt == '{' && *(fmt + 1) == '{') {
66 buffer_ += '{';
67 fmt += 2;
68 continue;
69 }
70 if (*fmt == '}' && *(fmt + 1) == '}') {
71 buffer_ += '}';
72 fmt += 2;
73 continue;
74 }
75
76 buffer_ += *fmt++;
77 }
78 }
79};
80
81} // namespace std
82#endif
Str which keeps the data on the heap. We grow the allocated memory only if the copy source is not fit...
Definition Str.h:24
virtual const char * c_str()
provides the string value as const char*
Definition StrView.h:456
Drop in pre c++20 Fromatter replacement for Arduino that supports {} placeholders and escaped {{}} br...
Definition Format.h:20
const char * c_str()
Returns raw C-string pointer suitable for Serial.println() or C APIs.
Definition Format.h:28
Format(const char *fmt, Args... args)
Definition Format.h:23
Definition InitializerList.h:7