Function format

Synopsis

#include <src/c4/format.hpp>

template <class Arg, class... Args>
size_t format(substr buf, csubstr fmt, Arg const &C4_RESTRICT a, Args const &C4_RESTRICT ...more)

Description

using a format string, serialize the arguments into the given fixed-size buffer. The buffer size is strictly respected: no writes will occur beyond its end. In the format string, each argument is marked with a compact curly-bracket pair: {}. Arguments beyond the last curly bracket pair are silently ignored. For example:

c4::format(buf, "the {} drank {} {}", "partier", 5, "beers"); // the partier drank 5 beers
c4::format(buf, "the {} drank {} {}", "programmer", 6, "coffees"); // the programmer drank 6 coffees
Returns
the number of characters needed to write into the buffer.
See
c4::formatrs() if instead of a fixed-size buffer, a resizeable container is desired
See
c4::unformat() for the inverse function
See
c4::cat() if no format or separator is needed
See
c4::catsep() if no format is needed, but a separator must be used

Mentioned in

Source

Lines 618-635 in src/c4/format.hpp.

template<class Arg, class... Args>
size_t format(substr buf, csubstr fmt, Arg const& C4_RESTRICT a, Args const& C4_RESTRICT ...more)
{
    auto pos = fmt.find("{}"); // @todo use _find_fmt()
    if(C4_UNLIKELY(pos == csubstr::npos))
    {
        return format(buf, fmt);
    }
    size_t num = to_chars(buf, fmt.sub(0, pos));
    size_t out = num;
    buf  = buf.len >= num ? buf.sub(num) : substr{};
    num  = to_chars(buf, a);
    out += num;
    buf  = buf.len >= num ? buf.sub(num) : substr{};
    num  = format(buf, fmt.sub(pos + 2), more...);
    out += num;
    return out;
}





Add Discussion as Guest

Log in