GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
formatting.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_FORMATTING_HPP
5#define GREM_CORE_FORMATTING_HPP
6
8
9#include <GREM/core/Error.hpp>
21
22#include <charconv> // std::chars_format, std::to_chars_result, std::to_chars
23#include <cmath> // std::isfinite
24#include <cstdio> // EOF, stdout, stderr, std::FILE, std::fwrite, std::fputc
25#include <iosfwd> // std::ostream
26#include <iterator> // std::begin, std::end
27#include <system_error> // std::errc
28#include <type_traits> // std::make_unsigned_t, std::type_identity_t, std::is_array_v
29#include <utility> // std::move, std::index_sequence, std::make_index_sequence
30
31namespace grem {
32
33namespace detail {
34struct Unformattable {};
35} // namespace detail
36
38 using Error::Error;
39};
40
42public:
43 constexpr virtual void append(StringView string) = 0;
44};
45
46template <typename T>
47struct Formatter {
48 using GREM_private_UnformattableTag = void;
49
50 [[nodiscard]] constexpr const char* parseFormatSpecification(const auto& p) {
52 "Argument type lacks a formatter. Implement one by specializing grem::Formatter<T>. See bottom of <GREM/core/formatting.hpp> for examples.");
53 return p;
54 }
55
56 void formatTo(FormatOutput& output, const auto& value) const {
58 "Argument type lacks a formatter. Implement one by specializing grem::Formatter<T>. See bottom of <GREM/core/formatting.hpp> for examples.");
59 (void)output;
60 (void)value;
61 }
62};
63
64namespace detail {
65
66struct FormatSizeCounter : FormatOutput {
67 size_t output = 0;
68
69 constexpr void append(StringView string) override {
70 output += string.size();
71 }
72};
73
74template <typename It>
75struct IteratorFormatWriter : FormatOutput {
76 It output;
77
78 constexpr IteratorFormatWriter(It output)
79 : output(output) {}
80
81 constexpr void append(StringView string) override {
82 for (const char ch : string) {
83 *output++ = ch;
84 }
85 }
86};
87
88struct CFileFormatWriter : FormatOutput {
89 std::FILE* output;
90
91 constexpr CFileFormatWriter(std::FILE* output)
92 : output(output) {}
93
94 void append(StringView string) override {
95 if (std::fwrite(string.data(), sizeof(char), string.size(), output) != string.size()) {
96 throw FormatError{"Failed to write to file."};
97 }
98 }
99};
100
101struct StreamFormatWriter : FormatOutput {
102 std::ostream& output;
103
104 constexpr StreamFormatWriter(std::ostream& output)
105 : output(output) {}
106
107 GREM_API(core) void append(StringView string) override;
108};
109
110template <typename Output>
111struct AppendingFormatWriter : FormatOutput {
112 Output& output;
113
114 constexpr AppendingFormatWriter(Output& output)
115 : output(output) {}
116
117 constexpr void append(StringView string) override {
118 output.append(string);
119 }
120};
121
122} // namespace detail
123
124template <typename T>
125concept formattable = requires(Formatter<T> formatter, const Formatter<T> constFormatter, const char* p, detail::FormatSizeCounter output, const T value) {
126 p = formatter.parseFormatSpecification(p);
127 constFormatter.formatTo(output, value);
128} && !requires { typename Formatter<T>::GREM_private_UnformattableTag; };
129
131public:
132 template <typename T, typename CustomFormatter>
133 [[nodiscard]] static constexpr FormatArgument createEmpty() noexcept {
134 FormatArgument result{};
135 result.parseFormatSpecificationAndFormatToImplementation = [](FormatOutput&, const char* p, ValueView) -> const char* {
136 CustomFormatter formatter{};
137 if (*p != '}') {
138 p = formatter.parseFormatSpecification(p);
139 }
140 return p;
141 };
142 return result;
143 };
144
145 template <typename T, typename CustomFormatter>
146 [[nodiscard]] static constexpr FormatArgument create(const T& value) noexcept {
147 constexpr bool IS_SMALL = !std::is_array_v<T> && trivially_copyable<T> && sizeof(T) <= sizeof(void*) && alignof(T) <= alignof(void*);
148 FormatArgument result{};
149 if constexpr (IS_SMALL) {
150 result.valueView = {.smallBuffer{}};
151 const ValueRepresentation<T> valueRepresentation = bit_cast<ValueRepresentation<T>>(value);
152 for (size_t i = 0; i < sizeof(T); ++i) {
153 result.valueView.smallBuffer[i] = valueRepresentation.bytes[i];
154 }
155 } else {
156 result.valueView = {.pointer = &value};
157 }
158 result.parseFormatSpecificationAndFormatToImplementation = [](FormatOutput& output, const char* p, ValueView valueView) -> const char* {
159 CustomFormatter formatter{};
160 if (*p != '}') {
161 p = formatter.parseFormatSpecification(p);
162 }
163 if constexpr (IS_SMALL) {
164 ValueRepresentation<T> valueRepresentation{};
165 for (size_t i = 0; i < sizeof(T); ++i) {
166 valueRepresentation.bytes[i] = valueView.smallBuffer[i];
167 }
168 formatter.formatTo(output, bit_cast<T>(valueRepresentation));
169 } else {
170 formatter.formatTo(output, *static_cast<const T*>(valueView.pointer));
171 }
172 return p;
173 };
174 return result;
175 };
176
177 template <typename T>
178 constexpr FormatArgument(const T& value) requires(!same_as<T, FormatArgument>) {
179 *this = create<T, Formatter<T>>(value);
180 }
181
182 [[nodiscard]] constexpr const char* parseFormatSpecificationAndFormatTo(FormatOutput& output, const char* p) const {
183 return parseFormatSpecificationAndFormatToImplementation(output, p, valueView);
184 }
185
186private:
187 union ValueView {
188 const void* pointer;
189 alignas(void*) byte smallBuffer[sizeof(void*)];
190 };
191
192 ValueView valueView{.pointer = nullptr};
193 const char* (*parseFormatSpecificationAndFormatToImplementation)(FormatOutput& output, const char* p, ValueView valueView) = nullptr;
194
195 constexpr FormatArgument() noexcept = default;
196};
197
199
200constexpr void formatToV(FormatOutput& output, CStringView format, FormatArguments arguments) {
201 size_t nextImplicitArgumentIndex = 0;
202
203 const char* p = format.c_str();
204 const char* begin = p;
205 while (true) {
206 switch (*p) {
207 case '\0': output.append(StringView{begin, p}); return;
208 case '}':
209 ++p;
210 if (*p == '}') {
211 output.append(StringView{begin, p});
212 ++p;
213 begin = p;
214 continue;
215 }
216 throw FormatError{"Misplaced '}' in format string."};
217 case '{': {
218 const char* const openCurly = p;
219 ++p;
220 if (*p == '{') {
221 output.append(StringView{begin, p});
222 ++p;
223 begin = p;
224 continue;
225 }
226 output.append(StringView{begin, openCurly});
227 size_t argumentIndex = 0;
228 if (*p >= '0' && *p <= '9') {
229 if (nextImplicitArgumentIndex != 0 && nextImplicitArgumentIndex != Limits<size_t>::MAX) {
230 throw FormatError{"Mixed explicit/implicit argument indices in format string."};
231 }
232 do {
233 argumentIndex *= 10;
234 argumentIndex += static_cast<size_t>(*p - '0');
235 ++p;
236 } while (*p >= '0' && *p <= '9');
237 nextImplicitArgumentIndex = Limits<size_t>::MAX;
238 } else {
239 if (nextImplicitArgumentIndex == Limits<size_t>::MAX) {
240 throw FormatError{"Mixed explicit/implicit argument indices in format string."};
241 }
242 argumentIndex = nextImplicitArgumentIndex++;
243 }
244 if (*p == ':') {
245 ++p;
246 } else if (*p != '}') {
247 throw FormatError{"Invalid format argument specifier."};
248 }
249 if (argumentIndex >= arguments.size()) {
250 throw FormatError{"Missing format argument."};
251 }
252 const FormatArgument argument = arguments.begin()[argumentIndex];
253 p = argument.parseFormatSpecificationAndFormatTo(output, p);
254 if (*p != '}') {
255 throw FormatError{"Invalid format argument specifier."};
256 }
257 ++p;
258 begin = p;
259 break;
260 }
261 default: ++p; break;
262 }
263 }
264}
265
267 constexpr explicit RuntimeFormat(CStringView format) noexcept
268 : CStringView(format) {}
269};
270
271template <typename... Args>
273public:
274 template <typename T>
275 consteval FormatStringBase(const T& format) requires(convertible_to<T, CStringView>)
276 : format(format) {
277 detail::FormatSizeCounter sizeCounter{};
279 }
280
281 constexpr FormatStringBase(RuntimeFormat format) noexcept
282 : format(format) {}
283
284 [[nodiscard]] constexpr CStringView get() const noexcept {
285 return format;
286 }
287
288private:
289 CStringView format;
290};
291
292template <typename... Args>
294
295template <typename... Args>
296[[nodiscard]] constexpr size_t getFormattedSize(FormatString<Args...> format, const Args&... args) {
297 detail::FormatSizeCounter sizeCounter{};
298 formatToV(sizeCounter, format.get(), {args...});
299 return sizeCounter.output;
300}
301
302template <typename Output, typename... Args>
303constexpr void formatTo(Output& output, FormatString<Args...> format, const Args&... args) {
304 if constexpr (requires(Output out, const size_t n) {
305 out.data();
306 out.size();
307 out.resize(n);
308 }) {
309 detail::FormatSizeCounter sizeCounter{};
310 formatToV(sizeCounter, format.get(), {args...});
311 const size_t formattedSize = sizeCounter.output;
312 const size_t offset = output.size();
313 output.resize(offset + formattedSize);
314 try {
315 char* p = output.data() + offset;
316 formatTo(p, format, args...);
317 } catch (...) {
318 output.resize(offset);
319 throw;
320 }
321 } else if constexpr (requires(Output out, const size_t n) {
322 out.size();
323 out.reserve(n);
324 }) {
325 detail::FormatSizeCounter sizeCounter{};
326 formatToV(sizeCounter, format.get(), {args...});
327 const size_t formattedSize = sizeCounter.output;
328 output.reserve(output.size() + formattedSize);
329 detail::AppendingFormatWriter writer{output};
330 formatToV(writer, format.get(), {args...});
331 } else if constexpr (requires { *output++ = '\0'; }) {
332 detail::IteratorFormatWriter writer{output};
333 formatToV(writer, format.get(), {args...});
334 output = writer.output;
335 } else {
336 detail::AppendingFormatWriter writer{output};
337 formatToV(writer, format.get(), {args...});
338 }
339}
340
341template <typename... Args>
342GREM_ALWAYS_INLINE void print(std::FILE* output, FormatString<Args...> format, const Args&... args) {
343 detail::CFileFormatWriter writer{output};
344 formatTo(writer, format, args...);
345}
346
347template <typename... Args>
348GREM_ALWAYS_INLINE void print(std::ostream& output, FormatString<Args...> format, const Args&... args) {
349 detail::StreamFormatWriter writer{output};
350 formatTo(writer, format, args...);
351}
352
353GREM_ALWAYS_INLINE void println(std::FILE* output) {
354 if (std::fputc('\n', output) == EOF) {
355 throw FormatError{"Failed to write to file."};
356 }
357}
358
359GREM_ALWAYS_INLINE void println(std::ostream& output) {
360 print(output, "\n");
361}
362
363template <typename... Args>
364GREM_ALWAYS_INLINE void println(std::FILE* output, FormatString<Args...> format, const Args&... args) {
365 print(output, format, args...);
366 println(output);
367}
368
369template <typename... Args>
370GREM_ALWAYS_INLINE void println(std::ostream& output, FormatString<Args...> format, const Args&... args) {
371 print(output, format, args...);
372 println(output);
373}
374
375template <typename... Args>
376GREM_ALWAYS_INLINE void print(FormatString<Args...> format, const Args&... args) {
377 print(stdout, format, args...);
378}
379
381 println(stdout);
382}
383
384template <typename... Args>
385GREM_ALWAYS_INLINE void println(FormatString<Args...> format, const Args&... args) {
386 println(stdout, format, args...);
387}
388
389template <typename... Args>
390GREM_ALWAYS_INLINE void eprint(FormatString<Args...> format, const Args&... args) {
391 print(stderr, format, args...);
392}
393
395 println(stderr);
396}
397
398template <typename... Args>
399GREM_ALWAYS_INLINE void eprintln(FormatString<Args...> format, const Args&... args) {
400 println(stderr, format, args...);
401}
402
447template <typename... Args>
448[[nodiscard]] inline String formatString(FormatString<Args...> format, const Args&... args) {
449 String result{};
450 formatTo(result, format, args...);
451 return result;
452}
453
454[[nodiscard]] inline String formatStringV(CStringView format, FormatArguments arguments) {
455 String result{};
456 detail::AppendingFormatWriter writer{result};
457 formatToV(writer, format, arguments);
458 return result;
459}
460
461namespace detail {
462
463template <size_t SmallCapacity>
464class SmallFormattedString {
465public:
466 SmallFormattedString() noexcept = default;
467
468 ~SmallFormattedString() {
469 if (length > SmallCapacity) {
470 delete[] characters;
471 }
472 }
473
474 SmallFormattedString(const SmallFormattedString& other)
475 : SmallFormattedString() {
476 *this = other;
477 }
478
479 SmallFormattedString(SmallFormattedString&& other) noexcept
480 : SmallFormattedString() {
481 *this = std::move(other);
482 }
483
484 SmallFormattedString& operator=(const SmallFormattedString& other) {
485 if (this == &other) {
486 return *this;
487 }
488 resize(other.size());
489 char* p = data();
490 for (const char ch : other) {
491 *p++ = ch;
492 }
493 return *this;
494 }
495
496 SmallFormattedString& operator=(SmallFormattedString&& other) noexcept {
497 if (this == &other) {
498 return *this;
499 }
500 if (length > SmallCapacity) {
501 delete[] characters;
502 }
503 if (other.length > SmallCapacity) {
504 characters = other.characters;
505 other.characters = other.smallBuffer;
506 } else {
507 char* p = smallBuffer;
508 for (const char ch : other) {
509 *p++ = ch;
510 }
511 characters = smallBuffer;
512 }
513 length = other.length;
514 other.length = 0;
515 return *this;
516 }
517
518 [[nodiscard]] GREM_ALWAYS_INLINE char* data() noexcept {
519 return characters;
520 }
521
522 [[nodiscard]] GREM_ALWAYS_INLINE const char* data() const noexcept {
523 return characters;
524 }
525
526 [[nodiscard]] GREM_ALWAYS_INLINE size_t size() const noexcept {
527 return length;
528 }
529
530 [[nodiscard]] GREM_ALWAYS_INLINE char* begin() noexcept {
531 return data();
532 }
533
534 [[nodiscard]] GREM_ALWAYS_INLINE const char* begin() const noexcept {
535 return data();
536 }
537
538 [[nodiscard]] GREM_ALWAYS_INLINE char* end() noexcept {
539 return data() + size();
540 }
541
542 [[nodiscard]] GREM_ALWAYS_INLINE const char* end() const noexcept {
543 return data() + size();
544 }
545
546 void resize(size_t newLength) {
547 if (newLength > length) {
548 if (newLength > SmallCapacity) {
549 char* const newCharacters = new char[newLength]; // NOLINT(cppcoreguidelines-owning-memory)
550 char* p = newCharacters;
551 for (const char ch : *this) {
552 *p++ = ch;
553 }
554 if (length > SmallCapacity) {
555 delete[] characters;
556 }
557 characters = newCharacters;
558 } else {
559 if (length > SmallCapacity) {
560 char* p = smallBuffer;
561 for (const char ch : *this) {
562 *p++ = ch;
563 }
564 delete[] characters;
565 characters = smallBuffer;
566 }
567 }
568 length = newLength;
569 } else if (newLength < length) {
570 if (newLength <= SmallCapacity && length > SmallCapacity) {
571 char* p = smallBuffer;
572 for (const char ch : *this) {
573 *p++ = ch;
574 }
575 delete[] characters;
576 characters = smallBuffer;
577 }
578 length = newLength;
579 }
580 }
581
582 constexpr operator StringView() const noexcept {
583 return StringView{characters, length};
584 }
585
586private:
587 char* characters = smallBuffer;
588 size_t length = 0;
589 char smallBuffer[SmallCapacity];
590};
591
592} // namespace detail
593
594template <size_t N, typename... Args>
595GREM_ALWAYS_INLINE detail::SmallFormattedString<N> formatSmallString(FormatString<Args...> format, const Args&... args) {
596 detail::SmallFormattedString<N> result{};
597 formatTo(result, format, args...);
598 return result;
599}
600
601template <typename T>
607
608 [[nodiscard]] constexpr const char* parseFormatSpecification(const char* p) {
609 if (*p == 'n') {
610 openingBracket = {};
611 closingBracket = {};
612 ++p;
613 }
614 if constexpr (requires {
615 underlying.separator = ": ";
616 underlying.openingBracket = {};
617 underlying.closingBracket = {};
618 }) {
619 if (*p == 'm') {
620 if (!openingBracket.empty()) {
621 openingBracket = "{";
622 closingBracket = "}";
623 }
624 underlying.separator = ": ";
625 underlying.openingBracket = {};
626 underlying.closingBracket = {};
627 ++p;
628 }
629 }
630 if constexpr (same_as<T, char>) {
631 if (*p == 's') {
632 separator = {};
633 openingBracket = {};
634 closingBracket = {};
635 ++p;
636 }
637 }
638 if (*p == ':') {
639 ++p;
640 p = underlying.parseFormatSpecification(p);
641 }
642 return p;
643 }
644
645 void formatTo(FormatOutput& output, const auto& value) const {
646 output.append(openingBracket);
647 auto it = std::begin(value);
648 auto end = std::end(value);
649 if (it != end) {
650 underlying.formatTo(output, *it++);
651 while (it != end) {
652 output.append(separator);
653 underlying.formatTo(output, *it++);
654 }
655 }
656 output.append(closingBracket);
657 }
658};
659
660} // namespace grem
661
662template <>
664 size_t minWidth = 0;
665 char fill = ' ';
666 char alignment = '<';
667
668 [[nodiscard]] constexpr const char* parseFormatSpecification(const char* p) {
669 switch (*p) {
670 case '\0': break;
671 case '<': [[fallthrough]];
672 case '>': [[fallthrough]];
673 case '^': alignment = *p++; break;
674 default:
675 switch (*(p + 1)) {
676 case '<': [[fallthrough]];
677 case '>': [[fallthrough]];
678 case '^':
679 fill = *p++;
680 alignment = *p++;
681 break;
682 default: break;
683 }
684 break;
685 }
686 while (*p >= '0' && *p <= '9') {
687 minWidth *= 10;
688 minWidth += static_cast<size_t>(*p - '0');
689 ++p;
690 }
691 return p;
692 }
693
694 void formatTo(FormatOutput& output, StringView value) const {
695 switch (alignment) {
696 case '<':
697 output.append(value);
698 for (size_t i = value.size(); i < minWidth; ++i) {
699 output.append(StringView{&fill, 1});
700 }
701 break;
702 case '>':
703 for (size_t i = value.size(); i < minWidth; ++i) {
704 output.append(StringView{&fill, 1});
705 }
706 output.append(value);
707 break;
708 case '^':
709 if (value.size() < minWidth) {
710 const size_t n = minWidth - value.size();
711 const size_t halfRoundedDown = n / 2;
712 const size_t halfRoundedUp = n - halfRoundedDown;
713 for (size_t i = 0; i < halfRoundedDown; ++i) {
714 output.append(StringView{&fill, 1});
715 }
716 output.append(value);
717 for (size_t i = 0; i < halfRoundedUp; ++i) {
718 output.append(StringView{&fill, 1});
719 }
720 } else {
721 output.append(value);
722 }
723 break;
724 default: unreachable();
725 }
726 }
727};
728
729template <>
733 }
734};
735
736template <>
737struct grem::Formatter<grem::String> : Formatter<StringView> {
738 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, const String& value) const {
740 }
741};
742
743template <grem::size_t Length>
744struct grem::Formatter<grem::ConstantString<char, Length>> : Formatter<StringView> {
748};
749
750template <>
751struct grem::Formatter<char> : Formatter<StringView> {
752 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, char value) const {
754 }
755};
756
757template <>
759 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, const char* value) const {
761 }
762};
763
764template <>
766 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, char* value) const {
767 Formatter<const char*>::formatTo(output, static_cast<const char*>(value));
768 }
769};
770
771template <grem::size_t N>
772struct grem::Formatter<char[N]> : Formatter<const char*> {
773 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, const char (&value)[N]) const {
774 Formatter<const char*>::formatTo(output, static_cast<const char*>(value));
775 }
776};
777
778template <>
779struct grem::Formatter<bool> : Formatter<StringView> {
780 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, bool value) const {
781 Formatter<StringView>::formatTo(output, (value) ? StringView{"true"} : StringView{"false"});
782 }
783};
784
785template <grem::strict_integral Integer>
786struct grem::Formatter<Integer> {
787 size_t minWidth = 0;
788 int radix = 10;
789 char fill = ' ';
790 char alignment = '\0';
791 char sign = '-';
792 bool addRadixPrefix = false;
793 bool makeUppercase = false;
794
795 [[nodiscard]] constexpr const char* parseFormatSpecification(const char* p) {
796 switch (*p) {
797 case '\0': break;
798 case '<': [[fallthrough]];
799 case '>': [[fallthrough]];
800 case '^': alignment = *p++; break;
801 default:
802 switch (*(p + 1)) {
803 case '<': [[fallthrough]];
804 case '>': [[fallthrough]];
805 case '^':
806 fill = *p++;
807 alignment = *p++;
808 break;
809 default: break;
810 }
811 break;
812 }
813
814 switch (*p) {
815 case '-': ++p; break;
816 case '+': [[fallthrough]];
817 case ' ': sign = *p++; break;
818 default: break;
819 }
820
821 if (*p == '#') {
822 addRadixPrefix = true;
823 ++p;
824 }
825
826 if (*p == '0') {
827 if (alignment == '\0') {
828 alignment = '0';
829 }
830 ++p;
831 }
832
833 while (*p >= '0' && *p <= '9') {
834 minWidth *= 10;
835 minWidth += static_cast<size_t>(*p - '0');
836 ++p;
837 }
838
839 switch (*p) {
840 case 'B': makeUppercase = true; [[fallthrough]];
841 case 'b':
842 radix = 2;
843 ++p;
844 break;
845 case 'o':
846 radix = 8;
847 ++p;
848 break;
849 case 'd':
850 radix = 10;
851 ++p;
852 break;
853 case 'X': makeUppercase = true; [[fallthrough]];
854 case 'x':
855 radix = 16;
856 ++p;
857 break;
858 default: break;
859 }
860 return p;
861 }
862
863 void formatTo(FormatOutput& output, Integer value) const {
864 char buffer[128];
865
866 char* p = buffer;
867
868 using UnsignedInteger = std::make_unsigned_t<Integer>;
869 UnsignedInteger unsignedValue = static_cast<UnsignedInteger>(value);
870
871 if constexpr (signed_integral<Integer>) {
872 if (value < 0) {
873 *p++ = '-';
874 unsignedValue = static_cast<UnsignedInteger>(UnsignedInteger{0} - unsignedValue);
875 } else if (value != 0 && sign != '-') {
876 *p++ = sign;
877 }
878 } else if (value != 0 && sign != '-') {
879 *p++ = sign;
880 }
881
882 if (addRadixPrefix) {
883 switch (radix) {
884 case 2:
885 *p++ = '0';
886 *p++ = 'b';
887 break;
888 case 8:
889 if (value != 0) {
890 *p++ = '0';
891 }
892 break;
893 case 10: break;
894 case 16:
895 *p++ = '0';
896 *p++ = 'x';
897 break;
898 default: unreachable();
899 }
900 }
901
902 char* const numberBegin = p;
903 const std::to_chars_result result = std::to_chars(p, buffer + sizeof buffer, unsignedValue, radix);
904 if (result.ec != std::errc{}) {
905 throw FormatError{"Maximum number string length exceeded."};
906 }
907
908 char* const begin = buffer;
909 char* const end = result.ptr;
910
911 if (makeUppercase) {
912 for (p = begin; p != end; ++p) {
913 if (*p >= 'a' && *p <= 'z') {
914 *p = static_cast<char>(*p - ('a' - 'A'));
915 }
916 }
917 }
918
919 switch (alignment) {
920 case '<':
921 output.append(StringView{begin, end});
922 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
923 output.append(StringView{&fill, 1});
924 }
925 break;
926 case '\0': [[fallthrough]];
927 case '>':
928 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
929 output.append(StringView{&fill, 1});
930 }
931 output.append(StringView{begin, end});
932 break;
933 case '^':
934 if (const size_t width = static_cast<size_t>(end - begin); width < minWidth) {
935 const size_t n = minWidth - width;
936 const size_t halfRoundedDown = n / 2;
937 const size_t halfRoundedUp = n - halfRoundedDown;
938 for (size_t i = 0; i < halfRoundedDown; ++i) {
939 output.append(StringView{&fill, 1});
940 }
941 output.append(StringView{begin, end});
942 for (size_t i = 0; i < halfRoundedUp; ++i) {
943 output.append(StringView{&fill, 1});
944 }
945 } else {
946 output.append(StringView{begin, end});
947 }
948 break;
949 case '0':
950 output.append(StringView{begin, numberBegin});
951 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
952 output.append(StringView{&alignment, 1});
953 }
954 output.append(StringView{numberBegin, end});
955 break;
956 default: unreachable();
957 }
958 }
959};
960
961template <grem::floating_point Float>
962struct grem::Formatter<Float> {
963 size_t minWidth = 0;
964 int precision = -1;
965 char fill = ' ';
966 char alignment = '\0';
967 char sign = '-';
968 char presentationType = '\0';
969 bool makeUppercase = false;
970 bool ensureDecimalPoint = false;
971
972 [[nodiscard]] constexpr const char* parseFormatSpecification(const char* p) {
973 switch (*p) {
974 case '\0': break;
975 case '<': [[fallthrough]];
976 case '>': [[fallthrough]];
977 case '^': alignment = *p++; break;
978 default:
979 switch (*(p + 1)) {
980 case '<': [[fallthrough]];
981 case '>': [[fallthrough]];
982 case '^':
983 fill = *p++;
984 alignment = *p++;
985 break;
986 default: break;
987 }
988 break;
989 }
990
991 switch (*p) {
992 case '-': ++p; break;
993 case '+': [[fallthrough]];
994 case ' ': sign = *p++; break;
995 default: break;
996 }
997
998 if (*p == '#') {
999 ensureDecimalPoint = true;
1000 ++p;
1001 }
1002
1003 if (*p == '0') {
1004 if (alignment == '\0') {
1005 alignment = '0';
1006 }
1007 ++p;
1008 }
1009
1010 while (*p >= '0' && *p <= '9') {
1011 minWidth *= 10;
1012 minWidth += static_cast<size_t>(*p - '0');
1013 ++p;
1014 }
1015
1016 if (*p == '.') {
1017 ++p;
1018 if (*p < '0' || *p > '9') {
1019 throw FormatError{"Invalid precision specifier."};
1020 }
1021 precision = 0;
1022 do {
1023 precision *= 10;
1024 precision += static_cast<size_t>(*p - '0');
1025 ++p;
1026 } while (*p >= '0' && *p <= '9');
1027 }
1028
1029 switch (*p) {
1030 case 'A': [[fallthrough]];
1031 case 'E': [[fallthrough]];
1032 case 'F': [[fallthrough]];
1033 case 'G': makeUppercase = true; [[fallthrough]];
1034 case 'a': [[fallthrough]];
1035 case 'e': [[fallthrough]];
1036 case 'f': [[fallthrough]];
1037 case 'g': presentationType = *p++; break;
1038 default: break;
1039 }
1040 return p;
1041 }
1042
1043 void formatTo(FormatOutput& output, Float value) const {
1044 char buffer[256];
1045
1046 char* p = buffer;
1047 const char* numberBegin = p;
1048 if (value < Float{}) {
1049 ++numberBegin;
1050 } else if (value != 0 && sign != '-') {
1051 ++numberBegin;
1052 *p++ = sign;
1053 }
1054
1055 std::to_chars_result result{};
1056 switch (presentationType) {
1057 case '\0':
1058 if (precision < 0) {
1059 result = std::to_chars(p, buffer + sizeof buffer, value);
1060 } else {
1061 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::general, precision);
1062 }
1063 break;
1064 case 'A': [[fallthrough]];
1065 case 'a':
1066 if (precision < 0) {
1067 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::hex);
1068 } else {
1069 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::hex, precision);
1070 }
1071 break;
1072 case 'E': [[fallthrough]];
1073 case 'e':
1074 if (precision < 0) {
1075 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::scientific);
1076 } else {
1077 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::scientific, precision);
1078 }
1079 break;
1080 case 'F': [[fallthrough]];
1081 case 'f':
1082 if (precision < 0) {
1083 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::fixed);
1084 } else {
1085 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::fixed, precision);
1086 }
1087 break;
1088 case 'G': [[fallthrough]];
1089 case 'g':
1090 if (precision < 0) {
1091 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::general);
1092 } else {
1093 result = std::to_chars(p, buffer + sizeof buffer, value, std::chars_format::general, precision);
1094 }
1095 break;
1096 default: unreachable();
1097 }
1098
1099 if (result.ec != std::errc{}) {
1100 throw FormatError{"Maximum number string length exceeded."};
1101 }
1102
1103 char* const begin = buffer;
1104 char* end = result.ptr;
1105
1106 if (makeUppercase) {
1107 for (p = begin; p != end; ++p) {
1108 if (*p >= 'a' && *p <= 'z') {
1109 *p = static_cast<char>(*p - ('a' - 'A'));
1110 }
1111 }
1112 }
1113
1114 if (ensureDecimalPoint) {
1115 if (std::isfinite(value) && StringView{begin, end}.find('.') == StringView::npos) {
1116 if (static_cast<size_t>(end - begin) >= sizeof buffer) {
1117 throw FormatError{"Maximum number string length exceeded."};
1118 }
1119 *end++ = '.';
1120 }
1121 }
1122
1123 switch (alignment) {
1124 case '<':
1125 output.append(StringView{begin, end});
1126 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
1127 output.append(StringView{&fill, 1});
1128 }
1129 break;
1130 case '0':
1131 if (std::isfinite(value)) {
1132 output.append(StringView{begin, numberBegin});
1133 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
1134 output.append(StringView{&alignment, 1});
1135 }
1136 output.append(StringView{numberBegin, end});
1137 break;
1138 }
1139 [[fallthrough]];
1140 case '\0': [[fallthrough]];
1141 case '>':
1142 for (size_t width = static_cast<size_t>(end - begin); width < minWidth; ++width) {
1143 output.append(StringView{&fill, 1});
1144 }
1145 output.append(StringView{begin, end});
1146 break;
1147 case '^':
1148 if (const size_t width = static_cast<size_t>(end - begin); width < minWidth) {
1149 const size_t n = minWidth - width;
1150 const size_t halfRoundedDown = n / 2;
1151 const size_t halfRoundedUp = n - halfRoundedDown;
1152 for (size_t i = 0; i < halfRoundedDown; ++i) {
1153 output.append(StringView{&fill, 1});
1154 }
1155 output.append(StringView{begin, end});
1156 for (size_t i = 0; i < halfRoundedUp; ++i) {
1157 output.append(StringView{&fill, 1});
1158 }
1159 } else {
1160 output.append(StringView{begin, end});
1161 }
1162 break;
1163 default: unreachable();
1164 }
1165 }
1166};
1167
1168template <>
1170 [[nodiscard]] GREM_ALWAYS_INLINE constexpr const char* parseFormatSpecification(const char* p) {
1171 radix = 16;
1173 }
1174
1175 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, const void* value) const {
1176 Formatter<uintptr_t>::formatTo(output, reinterpret_cast<uintptr_t>(value));
1177 }
1178};
1179
1180template <>
1182 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, void* value) const {
1183 Formatter<const void*>::formatTo(output, static_cast<const void*>(value));
1184 }
1185};
1186
1187template <>
1188struct grem::Formatter<std::nullptr_t> : Formatter<const void*> {
1189 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, std::nullptr_t value) const {
1190 Formatter<const void*>::formatTo(output, static_cast<const void*>(value));
1191 }
1192};
1193
1194template <>
1197 Formatter<bool>::formatTo(output, static_cast<bool>(value));
1198 }
1199};
1200
1201template <>
1204 Formatter<bool>::formatTo(output, static_cast<bool>(value));
1205 }
1206};
1207
1208template <>
1211 Formatter<bool>::formatTo(output, static_cast<bool>(value));
1212 }
1213};
1214
1215template <>
1218 Formatter<float>::formatTo(output, static_cast<float>(value));
1219 }
1220};
1221
1222template <>
1224 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, i8norm value) const {
1225 Formatter<float>::formatTo(output, static_cast<float>(value));
1226 }
1227};
1228
1229template <>
1231 GREM_ALWAYS_INLINE void formatTo(FormatOutput& output, u8norm value) const {
1232 Formatter<float>::formatTo(output, static_cast<float>(value));
1233 }
1234};
1235
1236template <>
1239 Formatter<float>::formatTo(output, static_cast<float>(value));
1240 }
1241};
1242
1243template <>
1246 Formatter<float>::formatTo(output, static_cast<float>(value));
1247 }
1248};
1249
1250template <grem::input_range Range>
1252 using GREM_private_DefaultRangeFormatterTag = void;
1253};
1254
1255template <grem::formattable... Ts>
1256struct grem::Formatter<grem::Tuple<Ts...>> {
1261
1262 [[nodiscard]] constexpr const char* parseFormatSpecification(const char* p) {
1263 switch (*p) {
1264 case 'm':
1265 if constexpr (sizeof...(Ts) == 2) {
1266 separator = ": ";
1267 openingBracket = {};
1268 closingBracket = {};
1269 ++p;
1270 } else {
1271 throw FormatError{"Invalid format specification."};
1272 }
1273 break;
1274 case 'n':
1275 separator = {};
1276 openingBracket = {};
1277 closingBracket = {};
1278 break;
1279 default: break;
1280 }
1281 return p;
1282 }
1283
1284 void formatTo(FormatOutput& output, const auto& value) const {
1285 output.append(openingBracket);
1286 if (sizeof...(Ts) > 0) {
1287 get<0>(underlying).formatTo(output, get<0>(value));
1288 [&]<size_t... Indices>(std::index_sequence<Indices...>) -> void {
1289 ((output.append(separator), get<1 + Indices>(underlying).formatTo(output, get<1 + Indices>(value))), ...);
1290 }(std::make_index_sequence<sizeof...(Ts) - 1>{});
1291 }
1292 output.append(closingBracket);
1293 }
1294};
1295
1296template <grem::formattable T1, grem::formattable T2>
1297struct grem::Formatter<grem::Pair<T1, T2>> : Formatter<grem::Tuple<T1, T2>> {};
1298
1299#endif
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
Definition ConstantString.hpp:40
Error(CStringView message)
Definition Error.hpp:55
Definition formatting.hpp:130
static constexpr FormatArgument create(const T &value) noexcept
Definition formatting.hpp:146
constexpr FormatArgument(const T &value)
Definition formatting.hpp:178
constexpr const char * parseFormatSpecificationAndFormatTo(FormatOutput &output, const char *p) const
Definition formatting.hpp:182
static constexpr FormatArgument createEmpty() noexcept
Definition formatting.hpp:133
Definition formatting.hpp:41
virtual constexpr void append(StringView string)=0
Definition formatting.hpp:272
constexpr FormatStringBase(RuntimeFormat format) noexcept
Definition formatting.hpp:281
consteval FormatStringBase(const T &format)
Definition formatting.hpp:275
constexpr CStringView get() const noexcept
Definition formatting.hpp:284
Definition Span.hpp:146
Definition Tuple.hpp:210
Definition fundamentals.hpp:86
Definition fundamentals.hpp:109
Definition fundamentals.hpp:132
Definition concepts.hpp:47
Definition formatting.hpp:125
Definition concepts.hpp:106
Definition concepts.hpp:35
Definition concepts.hpp:73
Definition concepts.hpp:187
@ N
'n'
Definition keyboard.hpp:84
Definition aliases.hpp:9
constexpr tuple_element_t< Index, Pair< T1, T2 > > & get(Pair< T1, T2 > &t) noexcept
Definition Pair.hpp:202
GREM_ALWAYS_INLINE detail::SmallFormattedString< N > formatSmallString(FormatString< Args... > format, const Args &... args)
Definition formatting.hpp:595
Span< const FormatArgument > FormatArguments
Definition formatting.hpp:198
detail::NormalizedInteger< int16_t > i16norm
Definition fundamentals.hpp:378
constexpr void formatTo(Output &output, FormatString< Args... > format, const Args &... args)
Definition formatting.hpp:303
FormatStringBase< std::type_identity_t< Args >... > FormatString
Definition formatting.hpp:293
String formatStringV(CStringView format, FormatArguments arguments)
Definition formatting.hpp:454
detail::NormalizedInteger< uint8_t > u8norm
Definition fundamentals.hpp:377
detail::NormalizedInteger< uint16_t > u16norm
Definition fundamentals.hpp:379
iter_value_t< iterator_t< T > > range_value_t
Definition concepts.hpp:222
constexpr void formatToV(FormatOutput &output, CStringView format, FormatArguments arguments)
Definition formatting.hpp:200
String formatString(FormatString< Args... > format, const Args &... args)
Format specification syntax examples:
Definition formatting.hpp:448
GREM_ALWAYS_INLINE void println()
Definition formatting.hpp:380
detail::NormalizedInteger< int8_t > i8norm
Definition fundamentals.hpp:376
constexpr size_t getFormattedSize(FormatString< Args... > format, const Args &... args)
Definition formatting.hpp:296
void unreachable()
Definition assertions.hpp:125
StringBase< char, std::char_traits< char >, std::allocator< char > > String
Definition String.hpp:17
StringViewBase< char, std::char_traits< char > > StringView
Definition StringView.hpp:16
GREM_ALWAYS_INLINE void eprintln()
Definition formatting.hpp:394
GREM_ALWAYS_INLINE constexpr T GREM_VECTORCALL length(T a)
Definition math.hpp:2001
GREM_ALWAYS_INLINE void print(std::FILE *output, FormatString< Args... > format, const Args &... args)
Definition formatting.hpp:342
GREM_ALWAYS_INLINE void eprint(FormatString< Args... > format, const Args &... args)
Definition formatting.hpp:390
CStringViewBase< char, std::char_traits< char > > CStringView
Definition CStringView.hpp:635
Definition formatting.hpp:37
Error(CStringView message)
Definition Error.hpp:55
bool makeUppercase
Definition formatting.hpp:969
bool ensureDecimalPoint
Definition formatting.hpp:970
char presentationType
Definition formatting.hpp:968
char fill
Definition formatting.hpp:965
char sign
Definition formatting.hpp:967
int precision
Definition formatting.hpp:964
char alignment
Definition formatting.hpp:966
constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:972
size_t minWidth
Definition formatting.hpp:963
void formatTo(FormatOutput &output, Float value) const
Definition formatting.hpp:1043
bool makeUppercase
Definition formatting.hpp:793
char fill
Definition formatting.hpp:789
size_t minWidth
Definition formatting.hpp:787
int radix
Definition formatting.hpp:788
bool addRadixPrefix
Definition formatting.hpp:792
char alignment
Definition formatting.hpp:790
void formatTo(FormatOutput &output, Integer value) const
Definition formatting.hpp:863
constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:795
char sign
Definition formatting.hpp:791
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, bool value) const
Definition formatting.hpp:780
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, char value) const
Definition formatting.hpp:752
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, char *value) const
Definition formatting.hpp:766
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, const char(&value)[N]) const
Definition formatting.hpp:773
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, const char *value) const
Definition formatting.hpp:759
GREM_ALWAYS_INLINE constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:1170
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, const void *value) const
Definition formatting.hpp:1175
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, CStringView value) const
Definition formatting.hpp:731
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, const ConstantString< char, Length > &value) const
Definition formatting.hpp:745
void formatTo(FormatOutput &output, StringView value) const
Definition formatting.hpp:694
constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:668
size_t minWidth
Definition formatting.hpp:664
char alignment
Definition formatting.hpp:666
char fill
Definition formatting.hpp:665
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, const String &value) const
Definition formatting.hpp:738
void formatTo(FormatOutput &output, const auto &value) const
Definition formatting.hpp:1284
StringView openingBracket
Definition formatting.hpp:1259
constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:1262
StringView closingBracket
Definition formatting.hpp:1260
StringView separator
Definition formatting.hpp:1258
Tuple< Formatter< std::remove_cvref_t< Ts > >... > underlying
Definition formatting.hpp:1257
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, bool16_t value) const
Definition formatting.hpp:1196
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, bool32_t value) const
Definition formatting.hpp:1203
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, bool64_t value) const
Definition formatting.hpp:1210
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, float16_t value) const
Definition formatting.hpp:1217
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, i16norm value) const
Definition formatting.hpp:1238
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, i8norm value) const
Definition formatting.hpp:1224
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, u16norm value) const
Definition formatting.hpp:1245
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, u8norm value) const
Definition formatting.hpp:1231
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, std::nullptr_t value) const
Definition formatting.hpp:1189
GREM_ALWAYS_INLINE void formatTo(FormatOutput &output, void *value) const
Definition formatting.hpp:1182
Definition formatting.hpp:47
constexpr const char * parseFormatSpecification(const auto &p)
Definition formatting.hpp:50
void formatTo(FormatOutput &output, const auto &value) const
Definition formatting.hpp:56
static constexpr T MAX
Definition fundamentals.hpp:29
Definition Pair.hpp:53
Definition formatting.hpp:602
StringView separator
Definition formatting.hpp:604
StringView openingBracket
Definition formatting.hpp:605
void formatTo(FormatOutput &output, const auto &value) const
Definition formatting.hpp:645
Formatter< T > underlying
Definition formatting.hpp:603
StringView closingBracket
Definition formatting.hpp:606
constexpr const char * parseFormatSpecification(const char *p)
Definition formatting.hpp:608
Definition formatting.hpp:266
constexpr RuntimeFormat(CStringView format) noexcept
Definition formatting.hpp:267
Definition fundamentals.hpp:70
byte bytes[sizeof(T)]
Definition fundamentals.hpp:71
Definition fundamentals.hpp:160