format_it: Iterator based string formatting

format_it is my attempt at writing string formatting that is good enough that it could make it into the C++ standard. It’s not quite there yet but I haven’t gotten to work on it in a few months, so I will publish what I have so far. It is fast (much faster than using snprintf to write to the stack), type safe, memory safe, doesn’t truncate, extensible, backwards compatible for std::ostream and somewhat composable.

The syntax is a mix of printf, ostream and varargs. I’ll just show an example:

// format "100 and 0.5" into 1024 bytes of stack memory
fmt::stack_format<1024> format("%0 and %1", 100, 0.5f);

// print "Hello World" into 1024 bytes of stack memory
fmt::stack_print<1024> print("Hello", "World");

// prints "100 and 0.5\nHello World\n"
auto format_to_cout = fmt::make_format_it(std::ostreambuf_iterator<char>(std::cout));
*format_to_cout++ = format;
*format_to_cout++ = '\n';
*format_to_cout++ = print;
*format_to_cout++ = '\n';

Where the first and second struct mimic snprintf, and the third example introcues the formatting iterator that they use behind the scenes.

Read the rest of this entry »