[][src]Module const_format::fmt

This is supported on crate feature fmt only.

std::fmt-like api that can be used at compile-time.

Features

This module requires the "fmt" feature to be exported, and the nightly compiler, because at the time of writing these docs (2020-08-XX) mutable references in const fn require the unstable const_mut_refs feature.

Implementing the formatting methods

Users of this library can implement debug and display formatting by defining const_debug_fmt and const_display_fmt inherent methods with the

// use const_format::{Formatter, Error};
const fn const_debug_fmt(&self, &mut Formatter<'_>) -> Result<(), Error>
const fn const_display_fmt(&self, &mut Formatter<'_>) -> Result<(), Error>

signatures, and implementing the FormatMarker trait.

Limitations

Generic impls

Because the formatting of custom types is implemented with duck typing, it's not possible to format generic types, instead you must do either of these:

  • Provide all the implementations ahead of time, what impl_fmt is for.

  • Provide a macro that formats the type. The call_debug_fmt macro is a version of this that formats generic std types.

Formatting Syntax

The formatting macros all share the formatting syntax, modeled after the syntax of the formatting macros of the standard library.

Arguments

Arguments in the format string can be named and positional in these ways:

  • Implicitly positional(eg: formatc!("{}", 20u8)):
    Starts at the 0th positional argument and increments with every use.

  • Explicit positional(eg: formatc!("{0}", 10u8)).

  • Named, passed to the macro as named arguments (eg: formatc!("{foo}", foo = 10u8)).

  • Named, from constant (eg: formatc!("{FOO}")): Uses the FOO constant from the enclosing scope.

  • Named, from locals (eg: formatc!("{foo}")): Uses the foo local variable from the enclosing scope, only usable with the writec macro.

Formatters

The format arguments can be formatted in these ways:

  • Debug formatting (eg: formatc!("{:?}", 0u8) ):
    Similar to how Debug formatting in the standard library works, except that it does not escape unicode characters.

  • Display formatting (eg: formatc!("{}", 0u8), formatc!("{:}", 0u8) )

  • Hexadecimal formatting (eg: formatc!("{:x}", 0u8)): Writes numbers in capialized hexadecimal. This can be combined with debug formatting, with the "{:x?}" formatter.

  • Binary formatting (eg: formatc!("{:b}", 0u8)): This can be combined with debug formatting, with the "{:b?}" formatter.

Alternate flag

The alternate flag allows types to format themselves in an alternate way, written as "#" in a format string argument. eg:"{:#}", "{:#?}".

This is the built-in behavior for the alternate flag:

  • The Debug formater (eg: formatc!("{:#?}", FOO)): pretty print structs and enums.

  • The hexadecimal formater (eg: formatc!("{:#x}", FOO)): prefixes numbers with 0x.

  • The binary formater (eg: formatc!("{:#b}", FOO)): prefixes numbers with 0b.

Custom formatting

Arguments can access a Formatter for custom formatting with an |identifier| before the expression.

The expression will be evaluated every time it is used in the formatting string.

The expression can evaluate to either a () or a Result<(), const_format::Error>.

Note: this doesn't distinguish between debug and display formatting.

Link to full example of custom formatting

Examples

Derive

This example demonstrates how you can derive ConstDebug, and use it with the fmt API.

It uses the "derive" feature

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, PWrapper, StrWriter};
use const_format::{ConstDebug, strwriter_as_str, try_, unwrap, writec};

use std::ops::Range;

#[derive(ConstDebug)]
pub struct Foo {
    range: Option<Range<usize>>,
    point: Point,
}

#[derive(ConstDebug)]
pub struct Point {
    x: u32,
    y: u32,
}

const CAP: usize = 90;
const fn build_string() -> StrWriter<[u8; CAP]> {
    let mut writer = StrWriter::new([0; CAP]);

    let foo = Foo {
        range: Some(0..10),
        point: Point{ x: 13, y: 21 },
    };

    unwrap!(writec!(writer, "{:x?}", foo));

    writer
}

const STRING: &str = {
    const STR: &StrWriter<[u8; CAP]> = &build_string();
    strwriter_as_str!(STR)
};

// The formatter
assert_eq!(
    STRING,
    "Foo { range: Some(0..A), point: Point { x: D, y: 15 } }",
);

No proc macros

This example demonstrates how you can use the fmt api without using any proc macros.

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, PWrapper, StrWriter};
use const_format::{call_debug_fmt, coerce_to_fmt, impl_fmt, strwriter_as_str, try_};

use std::cmp::Ordering;

pub struct Foo<T, U> {
    a: u32,
    b: u32,
    c: T,
    d: [Ordering; 3],
    ignored: U,
}

//
impl_fmt!{
    // The type parameters of the impl must be written with trailing commas
    impl[U,] Foo<u32, U>;
    impl[U,] Foo<&str, U>;

    pub const fn const_debug_fmt(&mut self, f: &mut Formatter<'_>) -> Result<(), Error> {
        let mut f = f.debug_struct("Foo");

        // PWrapper is a wrapper for std types, which defines the formatter methods for them.
        try_!(PWrapper(self.a).const_debug_fmt(f.field("a")));

        try_!(PWrapper(self.b).const_debug_fmt(f.field("b")));

        // The `coerce_to_fmt` macro automatically wraps std types in `PWrapper`
        // and does nothing with non-std types.
        try_!(coerce_to_fmt!(self.c).const_debug_fmt(f.field("c")));

        // This macro allows debug formatting of some generic types which
        // wrap non-std types, including:
        // - arrays   - slices    - Option    - newtype wrappers
        call_debug_fmt!(array, self.d, f.field("d"));

        f.finish()
    }
}

const CAP: usize = 128;

const fn build_string() -> StrWriter<[u8; CAP]> {
    let flags = FormattingFlags::NEW.set_alternate(true);
    let mut writer = StrWriter::new([0; CAP]);

    const_format::unwrap!(
        Foo {
            a: 5,
            b: 8,
            c: 13,
            d: [Ordering::Less, Ordering::Equal, Ordering::Greater],
            ignored: (),
        }.const_debug_fmt(&mut Formatter::from_sw(&mut writer, flags))
    );

    writer
}

const STRING: &str = {
    const S: &StrWriter<[u8; CAP]> = &build_string();
    strwriter_as_str!(S)
};

assert_eq!(
    STRING,
    "\
Foo {
    a: 5,
    b: 8,
    c: 13,
    d: [
        Less,
        Equal,
        Greater,
    ],
}\
    ",
);

Custom formatting

This example demonstrates how you can do custom formatting, by using a Formatter directly.

#![feature(const_mut_refs)]

use const_format::{call_debug_fmt, formatc};

// Positional argument
assert_eq!(formatc!("{}", |fmt| fmt.write_ascii_repeated(b'a', 4) ), "aaaa");

// Named argument
assert_eq!(formatc!("{foo}", foo = |fmt| fmt.write_ascii_repeated(b'0', 10) ), "0000000000");

// Repeating a positional argument multiple times
assert_eq!(formatc!("{0}{0}{0}", |fmt| fmt.write_str("hi") ), "hihihi");

// Using debug formatting is no different to display formatting:
assert_eq!(formatc!("{0:?}{0:?}{0:?}", |fmt| fmt.write_str("hi") ), "hihihi");

// But binary/hex formatting, and the alternate flag, do have an effect:
assert_eq!(
    formatc!(
        "{0}\n{0:x}\n{0:b}\n{0:#x}\n{0:#b}",
        |fmt| call_debug_fmt!(array, [3u8, 13], fmt),
    ),
    "\
        [3, 13]\n\
        [3, D]\n\
        [11, 1101]\n\
        [\n    0x3,\n    0xD,\n]\n\
        [\n    0b11,\n    0b1101,\n]\
    ",
);

Structs

ComputeStrLength

For computing how long a formatted string would be.

DebugList

For debug formatting a list/array.

DebugSet

For debug formatting a set.

DebugStruct

A helper struct for debug formatting a braced struct, or braced variant.

DebugTuple

For debug formatting a tuple struct, or tuple variant.

Formatter

A handle for writing formatted output.

FormattingFlags

This type bundles configuration for how to format data into strings, including.

StrWriter

A wrapper over an array usable to build up a &str at compile-time.

StrWriterMut

For writing a formatted string into a [u8].

ToResult

For converting types to const_format::Result

Enums

Error

An error while trying to write into a StrWriter.

NoEncoding

Marker type indicating that the StrWriterMut is arbitrary bytes, disabling the as_str method.

NumberFormatting

How numbers are formatted in debug formatters.

Utf8Encoding

Marker type indicating that the StrWriterMut is valid utf8, enabling the as_str method.

Type Definitions

Result

The return type of most formatting functions