4#ifndef GREM_CORE_FORMATTING_HPP
5#define GREM_CORE_FORMATTING_HPP
27#include <system_error>
34struct Unformattable {};
48 using GREM_private_UnformattableTag = void;
52 "Argument type lacks a formatter. Implement one by specializing grem::Formatter<T>. See bottom of <GREM/core/formatting.hpp> for examples.");
58 "Argument type lacks a formatter. Implement one by specializing grem::Formatter<T>. See bottom of <GREM/core/formatting.hpp> for examples.");
66struct FormatSizeCounter : FormatOutput {
69 constexpr void append(
StringView string)
override {
70 output +=
string.size();
75struct IteratorFormatWriter : FormatOutput {
78 constexpr IteratorFormatWriter(It output)
81 constexpr void append(
StringView string)
override {
82 for (
const char ch :
string) {
88struct CFileFormatWriter : FormatOutput {
91 constexpr CFileFormatWriter(std::FILE* output)
95 if (std::fwrite(
string.data(),
sizeof(
char),
string.size(), output) !=
string.size()) {
96 throw FormatError{
"Failed to write to file."};
101struct StreamFormatWriter : FormatOutput {
102 std::ostream& output;
104 constexpr StreamFormatWriter(std::ostream& output)
107 GREM_API(core)
void append(
StringView string)
override;
110template <
typename Output>
111struct AppendingFormatWriter : FormatOutput {
114 constexpr AppendingFormatWriter(Output& output)
117 constexpr void append(
StringView string)
override {
118 output.append(
string);
126 p = formatter.parseFormatSpecification(p);
127 constFormatter.formatTo(output, value);
128} && !
requires {
typename Formatter<T>::GREM_private_UnformattableTag; };
132 template <
typename T,
typename CustomFormatter>
135 result.parseFormatSpecificationAndFormatToImplementation = [](
FormatOutput&,
const char* p, ValueView) ->
const char* {
136 CustomFormatter formatter{};
138 p = formatter.parseFormatSpecification(p);
145 template <
typename T,
typename CustomFormatter>
147 constexpr bool IS_SMALL = !std::is_array_v<T> &&
trivially_copyable<T> &&
sizeof(T) <=
sizeof(
void*) &&
alignof(T) <=
alignof(
void*);
149 if constexpr (IS_SMALL) {
150 result.valueView = {.smallBuffer{}};
152 for (
size_t i = 0; i <
sizeof(T); ++i) {
153 result.valueView.smallBuffer[i] = valueRepresentation.
bytes[i];
156 result.valueView = {.pointer = &value};
158 result.parseFormatSpecificationAndFormatToImplementation = [](
FormatOutput& output,
const char* p, ValueView valueView) ->
const char* {
159 CustomFormatter formatter{};
161 p = formatter.parseFormatSpecification(p);
163 if constexpr (IS_SMALL) {
165 for (
size_t i = 0; i <
sizeof(T); ++i) {
166 valueRepresentation.
bytes[i] = valueView.smallBuffer[i];
168 formatter.formatTo(output, bit_cast<T>(valueRepresentation));
170 formatter.formatTo(output, *
static_cast<const T*
>(valueView.pointer));
177 template <
typename T>
183 return parseFormatSpecificationAndFormatToImplementation(output, p, valueView);
189 alignas(
void*)
byte smallBuffer[
sizeof(
void*)];
192 ValueView valueView{.pointer =
nullptr};
193 const char* (*parseFormatSpecificationAndFormatToImplementation)(FormatOutput& output,
const char* p, ValueView valueView) =
nullptr;
201 size_t nextImplicitArgumentIndex = 0;
203 const char* p = format.c_str();
204 const char* begin = p;
207 case '\0': output.append(
StringView{begin, p});
return;
216 throw FormatError{
"Misplaced '}' in format string."};
218 const char*
const openCurly = p;
227 size_t argumentIndex = 0;
228 if (*p >=
'0' && *p <=
'9') {
230 throw FormatError{
"Mixed explicit/implicit argument indices in format string."};
234 argumentIndex +=
static_cast<size_t>(*p -
'0');
236 }
while (*p >=
'0' && *p <=
'9');
240 throw FormatError{
"Mixed explicit/implicit argument indices in format string."};
242 argumentIndex = nextImplicitArgumentIndex++;
246 }
else if (*p !=
'}') {
247 throw FormatError{
"Invalid format argument specifier."};
249 if (argumentIndex >= arguments.size()) {
255 throw FormatError{
"Invalid format argument specifier."};
271template <
typename... Args>
274 template <
typename T>
277 detail::FormatSizeCounter sizeCounter{};
292template <
typename... Args>
295template <
typename... Args>
297 detail::FormatSizeCounter sizeCounter{};
299 return sizeCounter.output;
302template <
typename Output,
typename... Args>
304 if constexpr (
requires(Output out,
const size_t n) {
309 detail::FormatSizeCounter sizeCounter{};
311 const size_t formattedSize = sizeCounter.output;
312 const size_t offset = output.size();
313 output.resize(offset + formattedSize);
315 char* p = output.data() + offset;
318 output.resize(offset);
321 }
else if constexpr (
requires(Output out,
const size_t n) {
325 detail::FormatSizeCounter sizeCounter{};
327 const size_t formattedSize = sizeCounter.output;
328 output.reserve(output.size() + formattedSize);
329 detail::AppendingFormatWriter writer{output};
331 }
else if constexpr (
requires { *output++ =
'\0'; }) {
332 detail::IteratorFormatWriter writer{output};
334 output = writer.output;
336 detail::AppendingFormatWriter writer{output};
341template <
typename... Args>
343 detail::CFileFormatWriter writer{output};
347template <
typename... Args>
349 detail::StreamFormatWriter writer{output};
354 if (std::fputc(
'\n', output) == EOF) {
363template <
typename... Args>
365 print(output, format, args...);
369template <
typename... Args>
371 print(output, format, args...);
375template <
typename... Args>
377 print(stdout, format, args...);
384template <
typename... Args>
386 println(stdout, format, args...);
389template <
typename... Args>
391 print(stderr, format, args...);
398template <
typename... Args>
400 println(stderr, format, args...);
447template <
typename... Args>
456 detail::AppendingFormatWriter writer{result};
463template <
size_t SmallCapacity>
464class SmallFormattedString {
466 SmallFormattedString() noexcept = default;
468 ~SmallFormattedString() {
469 if (length > SmallCapacity) {
474 SmallFormattedString(
const SmallFormattedString& other)
475 : SmallFormattedString() {
479 SmallFormattedString(SmallFormattedString&& other) noexcept
480 : SmallFormattedString() {
481 *
this = std::move(other);
484 SmallFormattedString& operator=(
const SmallFormattedString& other) {
485 if (
this == &other) {
488 resize(other.size());
490 for (
const char ch : other) {
496 SmallFormattedString& operator=(SmallFormattedString&& other)
noexcept {
497 if (
this == &other) {
500 if (length > SmallCapacity) {
503 if (other.length > SmallCapacity) {
504 characters = other.characters;
505 other.characters = other.smallBuffer;
507 char* p = smallBuffer;
508 for (
const char ch : other) {
511 characters = smallBuffer;
539 return data() + size();
543 return data() + size();
546 void resize(
size_t newLength) {
547 if (newLength > length) {
548 if (newLength > SmallCapacity) {
549 char*
const newCharacters =
new char[newLength];
550 char* p = newCharacters;
551 for (
const char ch : *
this) {
554 if (length > SmallCapacity) {
557 characters = newCharacters;
559 if (length > SmallCapacity) {
560 char* p = smallBuffer;
561 for (
const char ch : *
this) {
565 characters = smallBuffer;
569 }
else if (newLength < length) {
570 if (newLength <= SmallCapacity && length > SmallCapacity) {
571 char* p = smallBuffer;
572 for (
const char ch : *
this) {
576 characters = smallBuffer;
582 constexpr operator StringView() const noexcept {
587 char* characters = smallBuffer;
589 char smallBuffer[SmallCapacity];
594template <
size_t N,
typename... Args>
596 detail::SmallFormattedString<N> result{};
614 if constexpr (
requires {
647 auto it = std::begin(value);
648 auto end = std::end(value);
671 case '<': [[fallthrough]];
672 case '>': [[fallthrough]];
676 case '<': [[fallthrough]];
677 case '>': [[fallthrough]];
686 while (*p >=
'0' && *p <=
'9') {
688 minWidth +=
static_cast<size_t>(*p -
'0');
698 for (
size_t i = value.size(); i <
minWidth; ++i) {
703 for (
size_t i = value.size(); i <
minWidth; ++i) {
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) {
717 for (
size_t i = 0; i < halfRoundedUp; ++i) {
743template <grem::
size_t Length>
771template <grem::
size_t N>
785template <grem::strict_
integral Integer>
798 case '<': [[fallthrough]];
799 case '>': [[fallthrough]];
803 case '<': [[fallthrough]];
804 case '>': [[fallthrough]];
815 case '-': ++p;
break;
816 case '+': [[fallthrough]];
817 case ' ':
sign = *p++;
break;
833 while (*p >=
'0' && *p <=
'9') {
835 minWidth +=
static_cast<size_t>(*p -
'0');
868 using UnsignedInteger = std::make_unsigned_t<Integer>;
869 UnsignedInteger unsignedValue =
static_cast<UnsignedInteger
>(value);
874 unsignedValue =
static_cast<UnsignedInteger
>(UnsignedInteger{0} - unsignedValue);
875 }
else if (value != 0 &&
sign !=
'-') {
878 }
else if (value != 0 &&
sign !=
'-') {
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."};
908 char*
const begin = buffer;
909 char*
const end = result.ptr;
912 for (p = begin; p != end; ++p) {
913 if (*p >=
'a' && *p <=
'z') {
914 *p =
static_cast<char>(*p - (
'a' -
'A'));
922 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
926 case '\0': [[fallthrough]];
928 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
934 if (
const size_t width =
static_cast<size_t>(end - begin); width <
minWidth) {
936 const size_t halfRoundedDown = n / 2;
937 const size_t halfRoundedUp = n - halfRoundedDown;
938 for (
size_t i = 0; i < halfRoundedDown; ++i) {
942 for (
size_t i = 0; i < halfRoundedUp; ++i) {
951 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
961template <grem::
floating_po
int Float>
975 case '<': [[fallthrough]];
976 case '>': [[fallthrough]];
980 case '<': [[fallthrough]];
981 case '>': [[fallthrough]];
992 case '-': ++p;
break;
993 case '+': [[fallthrough]];
994 case ' ':
sign = *p++;
break;
1010 while (*p >=
'0' && *p <=
'9') {
1012 minWidth +=
static_cast<size_t>(*p -
'0');
1018 if (*p <
'0' || *p >
'9') {
1019 throw FormatError{
"Invalid precision specifier."};
1024 precision +=
static_cast<size_t>(*p -
'0');
1026 }
while (*p >=
'0' && *p <=
'9');
1030 case 'A': [[fallthrough]];
1031 case 'E': [[fallthrough]];
1032 case 'F': [[fallthrough]];
1034 case 'a': [[fallthrough]];
1035 case 'e': [[fallthrough]];
1036 case 'f': [[fallthrough]];
1047 const char* numberBegin = p;
1048 if (value < Float{}) {
1050 }
else if (value != 0 &&
sign !=
'-') {
1055 std::to_chars_result result{};
1059 result = std::to_chars(p, buffer +
sizeof buffer, value);
1061 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::general,
precision);
1064 case 'A': [[fallthrough]];
1067 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::hex);
1069 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::hex,
precision);
1072 case 'E': [[fallthrough]];
1075 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::scientific);
1077 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::scientific,
precision);
1080 case 'F': [[fallthrough]];
1083 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::fixed);
1085 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::fixed,
precision);
1088 case 'G': [[fallthrough]];
1091 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::general);
1093 result = std::to_chars(p, buffer +
sizeof buffer, value, std::chars_format::general,
precision);
1099 if (result.ec != std::errc{}) {
1100 throw FormatError{
"Maximum number string length exceeded."};
1103 char*
const begin = buffer;
1104 char* end = result.ptr;
1107 for (p = begin; p != end; ++p) {
1108 if (*p >=
'a' && *p <=
'z') {
1109 *p =
static_cast<char>(*p - (
'a' -
'A'));
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."};
1126 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
1131 if (std::isfinite(value)) {
1133 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
1140 case '\0': [[fallthrough]];
1142 for (
size_t width =
static_cast<size_t>(end - begin); width <
minWidth; ++width) {
1148 if (
const size_t width =
static_cast<size_t>(end - begin); width <
minWidth) {
1150 const size_t halfRoundedDown = n / 2;
1151 const size_t halfRoundedUp = n - halfRoundedDown;
1152 for (
size_t i = 0; i < halfRoundedDown; ++i) {
1156 for (
size_t i = 0; i < halfRoundedUp; ++i) {
1250template <grem::input_range Range>
1252 using GREM_private_DefaultRangeFormatterTag = void;
1265 if constexpr (
sizeof...(Ts) == 2) {
1271 throw FormatError{
"Invalid format specification."};
1286 if (
sizeof...(Ts) > 0) {
1288 [&]<
size_t... Indices>(std::index_sequence<Indices...>) ->
void {
1290 }(std::make_index_sequence<
sizeof...(Ts) - 1>{});
1296template <grem::formattable T1, grem::formattable T2>
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
Definition ConstantString.hpp:40
Error(CStringView message)
Definition Error.hpp:55
Definition fundamentals.hpp:86
Definition fundamentals.hpp:109
Definition fundamentals.hpp:132
Definition concepts.hpp:47
Definition concepts.hpp:106
Definition concepts.hpp:35
Definition concepts.hpp:73
Definition concepts.hpp:187
@ N
'n'
Definition keyboard.hpp:84
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
static constexpr T MAX
Definition fundamentals.hpp:29
Definition fundamentals.hpp:70
byte bytes[sizeof(T)]
Definition fundamentals.hpp:71
Definition fundamentals.hpp:160