Consider the following snippet:
// #define USE_FMTLIB
#include <chrono>
#include <iostream>
#if defined(USE_FMTLIB)
#include <fmt/chrono.h>
#include <fmt/core.h>
#else
#include <format>
#endif
int main() {
constexpr std::size_t STATIC_BUFF_SIZE = 1024;
static char static_buff[STATIC_BUFF_SIZE];
const auto timepoint = std::chrono::system_clock::now();
const auto prefix_format_result =
#if defined(USE_FMTLIB)
fmt::format_to_n(
#else
std::format_to_n(
#endif
static_buff, STATIC_BUFF_SIZE,
"timestamp:{:%Y-%m-%d %H:%M:%S}",
timepoint
);
std::cout << (prefix_format_result.out - static_buff) << "\n";
}
(compilers keys are the default ones for g++ in compiler explorer: -std=c++20 -O3 -Wall -Wextra -pedantic -pedantic-errors
).
When USE_FMTLIB
is enabled (original fmt
is used for formatting) the code outputs 39. Otherwise, it outputs 1024 for g++ 13.2; for 13.3, 14.1, 14.2 and forth it outputs 39 (sometimes in compiler explorer compilation fails due to timeout).
fmt
and std
, format_to_n
returns struct containing two fields: size
and out
. Aren't they duplicate each other? I mean, if we know size
(the number of symbols written to buffer during formatting), we easily could compute out
(as I understand, it is pointer/iterator to position after formatted sequence) and vice versa.Notes
The libstdc++ implementation prior to GCC-13.3 had a bug in reporting the correct
format_to_n_result::out
value.
No, they don't duplicate each other. size
can be greater than n
if the output result is truncated.