Struct const_format::fmt::Formatter

source ·
pub struct Formatter<'w> { /* private fields */ }
Available on crate feature fmt only.
Expand description

A handle for writing formatted output.

Formatter writes utf8 encoded text, it can’t be used to write arbitrary bytes.

FormattingFlags

Types can change how they’re formatted based on the value returned by .flags(), for more details on that you can read the documentation for FormattingFlags.

Construction

This type can be constructed in these ways:

Errors

The write_* methods can only return an Error::NotEnoughSpace, when they do, the formatter was not written to, so you can try again with a shorter input.

In the case of the debug_* methods / the Debug* structs, they can return a Error::NotEnoughSpace when their finish method is called, not as soon as it happens.

Examples

Display formatting

This example demonstrates how you can do display formatting with a Formatter.

If you want to write a braced struct/variant you can use DebugStruct, or DebugTuple for tuple structs/variants.

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriter};
use const_format::{impl_fmt, try_};

struct Foo;

impl_fmt!{
    impl[] Foo;
     
    const fn const_display_fmt(&self, mut f: Formatter<'_>) -> Result<(), Error> {
        let string = "foo bar baz";
        try_!(f.write_u8_display(100));
        try_!(f.write_str(" "));
        try_!(f.write_str_range(string, 4..7));
        try_!(f.write_str("\n\n\n...figters"));
        Ok(())
    }
}

// We have to coerce `&mut StrWriter<[u8; 256]>` to `&mut StrWriter` to call the
// `make_formatter` method.
let writer: &mut StrWriter = &mut StrWriter::new([0; 256]);

let flags = FormattingFlags::NEW.set_binary();

// The Display formatters from this crate don't care which NumberFormatting you pass,
// they'll just write integers as decimal.
Foo.const_display_fmt(writer.make_formatter(flags));

assert_eq!(writer.as_str(), "100 bar\n\n\n...figters");

Writing to an array

This example demonstrates how you can use a Formatter to write to a byte slice.

You can use the from_custom constructor if you need to start writing from anywhere other than 0.

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriter};
use const_format::{impl_fmt, try_, writec};

const fn write_int(int: u32, buffer: &mut [u8]) -> Result<usize, Error> {
    let mut len = 0;
    let mut f = Formatter::from_custom_cleared(buffer, &mut len, FormattingFlags::NEW);
    try_!(writec!(f, "{0},{0:x},{0:b}", int));
    Ok(len)
}

let mut buffer = [0;64];

let written = write_int(17, &mut buffer).unwrap();

let string = std::str::from_utf8(&buffer[..written])
    .expect("Formatter only writes valid UTF8");

assert_eq!(string, "17,11,10001");

Implementations§

source§

impl<'w> Formatter<'w>

source

pub const fn from_sw(writer: &'w mut StrWriter, flags: FormattingFlags) -> Self

Constructs a Formatter.

Example
#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriter};
use const_format::try_;

const fn inner(mut f: Formatter<'_>) -> Result<(), Error> {
    try_!(f.write_str_range("ABCDEF", 2..4));
    try_!(f.write_str(" N"));
    try_!(f.write_ascii_repeated(b'o', 10));
    Ok(())
}

// We have to coerce `&mut StrWriter<[u8; 128]>` to `&mut StrWriter` to call the
// `as_str` method.
let writer: &mut StrWriter = &mut StrWriter::new([0; 128]);
inner(Formatter::from_sw(writer, FormattingFlags::NEW)).unwrap();

assert_eq!(writer.as_str(), "CD Noooooooooo");
source

pub const fn from_sw_mut<E: 'static>( writer: StrWriterMut<'w, E>, flags: FormattingFlags ) -> Self

Constructs a Formatter.

Example
#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriterMut};
use const_format::try_;

const fn inner(mut f: Formatter<'_>) -> Result<(), Error> {
    try_!(f.write_str_range("DVDVDVD", 2..5));
    try_!(f.write_str(" N"));
    try_!(f.write_ascii_repeated(b'o', 10));
    Ok(())
}

let mut len = 0;
let mut buffer = [0; 128];

let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

// We need to call `.reborrow()`, because otherwise the `StrWriterMut` is moved.
inner(Formatter::from_sw_mut(writer.reborrow(), FormattingFlags::NEW)).unwrap();

assert_eq!(writer.as_str(), "DVD Noooooooooo");
source

pub const fn from_custom( buffer: &'w mut [u8], length: &'w mut usize, flags: FormattingFlags ) -> Self

Construct a Formatter from a byte slice.

Formatter only writes utf8, which means that if &buffer[..length] is valid utf8, then buffer will continue to be utf8 after being written by the Formatter.

Example

This example demonstrates how you can use a Formatter to write to a byte slice that had some text written to it already.

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriter};
use const_format::{impl_fmt, try_, writec};

///
/// # Safety
///
/// `&buffer[..start]` must be valid utf8.
const fn write_int(
    int: u32,
    buffer: &mut [u8],
    start: usize,
) -> Result<usize, Error> {
    let mut len = start;
    let mut f = Formatter::from_custom(buffer, &mut len, FormattingFlags::NEW);
    try_!(writec!(f, "{0},{0:x},{0:b}", int));
    Ok(len)
}

let start_str = "The number is ";
let mut buffer = [0;64];
buffer[..start_str.len()].copy_from_slice(start_str.as_bytes());

let new_len = write_int(20, &mut buffer, start_str.len()).unwrap();

let string = std::str::from_utf8(&buffer[..new_len])
    .expect("Formatter only writes valid UTF8");

assert_eq!(string, "The number is 20,14,10100");
source

pub const fn from_custom_cleared( buffer: &'w mut [u8], length: &'w mut usize, flags: FormattingFlags ) -> Self

Construct a Formatterfrom a byte slice.

Example

For an example of using this method you can look at the type level docs

source

pub const fn flags(&self) -> FormattingFlags

Gets the formatting flags associated with this Formatter.

source

pub const fn margin(&self) -> usize

Gets how much indentation a data structure is printed with.

source§

impl<'w> Formatter<'w>

source

pub const fn borrow_mutably(&mut self) -> &mut Self

For borrowing this mutably in macros,just takes and returns a &mut Self.

source

pub const fn make_formatter(&mut self, flags: FormattingFlags) -> Formatter<'_>

Constructs a reborrow of this formatter, using flags as the formatting flags.

The return value inherits the margin from this Formatter.

This method exists because the writec macro gets a formatter from any writer by calling a make_formatter method.

Example

This example demonstrates how you can change the flags when writing a field.

#![feature(const_mut_refs)]

use const_format::{Error, Formatter, PWrapper};
use const_format::{coerce_to_fmt, formatc, impl_fmt, try_};

use std::ops::RangeInclusive;

struct Foo{
    x: u32,
    y: RangeInclusive<usize>,
    z: u32,
}

impl_fmt!{
    impl Foo;

    pub const fn const_debug_fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        let mut f = f.debug_struct("Foo");
        try_!(PWrapper(self.x).const_debug_fmt(f.field("x")));
         
        let mut fmt_y = f.field("y");
        let flags = fmt_y.flags().set_binary();
        try_!(coerce_to_fmt!(&self.y).const_debug_fmt(&mut fmt_y.make_formatter(flags)));

        try_!(PWrapper(self.z).const_debug_fmt(f.field("z")));
        f.finish()
    }
}

const FOO: Foo = Foo {
    x: 15,
    y: 16..=31,
    z: 32,
};
const S: &str = formatc!("{FOO:#?}");

const EXPECTED: &str = "\
Foo {
    x: 15,
    y: 0b10000..=0b11111,
    z: 32,
}\
";

assert_eq!(S, EXPECTED);
source

pub const fn debug_struct(&mut self, name: &str) -> DebugStruct<'_, 'w>

For debug writing a braced struct, or braced variant, taking its name as a parameter

Examples

For examples of using this method, you can look at the docs for DebugStruct

source

pub const fn debug_tuple(&mut self, name: &str) -> DebugTuple<'_, 'w>

For debug writing a tuple struct, or tuple variant,taking its name as a parameter

Examples

For examples of using this method, you can look at the docs for DebugTuple

source

pub const fn debug_list(&mut self) -> DebugList<'_, 'w>

For debug writing a list/array.

Examples

For examples of using this method, you can look at the docs for DebugList

source

pub const fn debug_set(&mut self) -> DebugSet<'_, 'w>

For debug writing a set.

Examples

For examples of using this method, you can look at the docs for DebugSet

source§

impl Formatter<'_>

source

pub const fn write_str_range( &mut self, string: &str, range: Range<usize> ) -> Result<(), Error>

Writes &string[range] into this Formatter.

This is a workaround for being unable to do &foo[start..end] at compile time.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_str_range("FOO BAR BAZ", 4..7);

assert_eq!(writer.as_str(), "BAR");
source

pub const fn write_str(&mut self, string: &str) -> Result<(), Error>

Writes string into this Formatter.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_str("FOO BAR BAZ");

assert_eq!(writer.as_str(), "FOO BAR BAZ");
source

pub const fn write_char(&mut self, character: char) -> Result<(), Error>

Writes character into this Formatter.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 4]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_char('a');
let _ = fmt.write_char('b');
let _ = fmt.write_char('c');

assert_eq!(writer.as_str(), "abc");
source

pub const fn write_ascii_range( &mut self, ascii: AsciiStr<'_>, range: Range<usize> ) -> Result<(), Error>

Writes &ascii[range] into this formatter.

This is a workaround for being unable to do &foo[start..end] at compile time.

Example

use const_format::{Formatter, FormattingFlags, StrWriter, ascii_str};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_ascii_range(ascii_str!("FOO BAR BAZ"), 4..7);

assert_eq!(writer.as_str(), "BAR");
source

pub const fn write_ascii(&mut self, ascii: AsciiStr<'_>) -> Result<(), Error>

Writes ascii into this formatter.

Example

use const_format::{Formatter, FormattingFlags, StrWriter, ascii_str};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_ascii(ascii_str!("FOO BAR BAZ"));

assert_eq!(writer.as_str(), "FOO BAR BAZ");
source

pub const fn write_ascii_repeated( &mut self, character: u8, repeated: usize ) -> Result<(), Error>

Writes the ascii character into this formatter repeated times.

If character is greater than 127, this writes character - 128 as an ascii character.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_ascii_repeated(b'A', 10);

assert_eq!(writer.as_str(), "AAAAAAAAAA");
source

pub const fn write_str_range_debug( &mut self, string: &str, range: Range<usize> ) -> Result<(), Error>

Writes string into this formatter, with debug formatting.

This is a workaround for being unable to do &foo[start..end] at compile time.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_str_range_debug("FOO\nBAR\tBAZ", 3..8);

assert_eq!(writer.as_str(), r#""\nBAR\t""#);
source

pub const fn write_str_debug(&mut self, string: &str) -> Result<(), Error>

Writes string into this formatter, with debug formatting.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_str_debug("FOO\nBAR\tBAZ");

assert_eq!(writer.as_str(), r#""FOO\nBAR\tBAZ""#);
source

pub const fn write_char_debug(&mut self, character: char) -> Result<(), Error>

Writes character into this Formatter, with debug formatting.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

let writer: &mut StrWriter = &mut StrWriter::new([0; 64]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_str(" ");
let _ = fmt.write_char_debug('\\');
let _ = fmt.write_str(" ");
let _ = fmt.write_char_debug('A');
let _ = fmt.write_str(" ");
let _ = fmt.write_char_debug('0');
let _ = fmt.write_str(" ");
let _ = fmt.write_char_debug('\'');
let _ = fmt.write_str(" ");

assert_eq!(writer.as_str(), r#" '\\' 'A' '0' '\'' "#);
source

pub const fn write_ascii_range_debug( &mut self, ascii: AsciiStr<'_>, range: Range<usize> ) -> Result<(), Error>

Writes &ascii[range] into this formatter, with debug formatting.

This is a workaround for being unable to do &foo[start..end] at compile time.

Example

use const_format::{Formatter, FormattingFlags, StrWriter, ascii_str};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_ascii_range_debug(ascii_str!("FOO\nBAR\tBAZ"), 3..8);

assert_eq!(writer.as_str(), r#""\nBAR\t""#);
source

pub const fn write_ascii_debug( &mut self, ascii: AsciiStr<'_> ) -> Result<(), Error>

Writes ascii into this formatter, with debug formatting.

Example

use const_format::{Formatter, FormattingFlags, StrWriter, ascii_str};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_ascii_debug(ascii_str!("FOO\nBAR\tBAZ"));

assert_eq!(writer.as_str(), r#""FOO\nBAR\tBAZ""#);
source

pub const fn write_u8_display(&mut self, n: u8) -> Result<(), Error>

Write n with display formatting.

Example

use const_format::{Formatter, FormattingFlags, StrWriter, ascii_str};

let writer: &mut StrWriter = &mut StrWriter::new([0; 16]);
let mut fmt = writer.make_formatter(FormattingFlags::NEW);

let _ = fmt.write_u8_display(13);
let _ = fmt.write_u8_display(21);
let _ = fmt.write_u8_display(34);

assert_eq!(writer.as_str(), "132134");
source§

impl Formatter<'_>

source

pub const fn write_u16_display(&mut self, n: u16) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_u32_display(&mut self, n: u32) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_u64_display(&mut self, n: u64) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_u128_display(&mut self, n: u128) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_usize_display(&mut self, n: usize) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_i8_display(&mut self, n: i8) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_i16_display(&mut self, n: i16) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_i32_display(&mut self, n: i32) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_i64_display(&mut self, n: i64) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_i128_display(&mut self, n: i128) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source

pub const fn write_isize_display(&mut self, n: isize) -> Result<(), Error>

Writes n with display formatting

For an example, you can look at the one for the write_u8_display method.

source§

impl Formatter<'_>

source

pub const fn write_u8_debug(&mut self, n: u8) -> Result<(), Error>

Writes n with debug formatting.

Example

use const_format::{Formatter, FormattingFlags, StrWriter};

fn debug_fmt(writer: &mut StrWriter, flag: FormattingFlags) -> &str {
    writer.clear();
    let mut fmt = Formatter::from_sw(writer, flag);
    let _ = fmt.write_u8_debug(63);
    writer.as_str()
}

let reg_flag = FormattingFlags::NEW.set_alternate(false);
let alt_flag = FormattingFlags::NEW.set_alternate(true);

let writer: &mut StrWriter = &mut StrWriter::new([0; 64]);

assert_eq!(debug_fmt(writer, reg_flag),                   "63"     );
assert_eq!(debug_fmt(writer, reg_flag.set_hexadecimal()), "3F"     );
assert_eq!(debug_fmt(writer, reg_flag.set_lower_hexadecimal()), "3f"     );
assert_eq!(debug_fmt(writer, reg_flag.set_binary()),      "111111" );
assert_eq!(debug_fmt(writer, alt_flag),                   "63"     );
assert_eq!(debug_fmt(writer, alt_flag.set_hexadecimal()), "0x3F"   );
assert_eq!(debug_fmt(writer, alt_flag.set_lower_hexadecimal()), "0x3f"   );
assert_eq!(debug_fmt(writer, alt_flag.set_binary()),      "0b111111");
source§

impl Formatter<'_>

source

pub const fn write_u16_debug(&mut self, n: u16) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_u32_debug(&mut self, n: u32) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_u64_debug(&mut self, n: u64) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_u128_debug(&mut self, n: u128) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_usize_debug(&mut self, n: usize) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_i8_debug(&mut self, n: i8) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_i16_debug(&mut self, n: i16) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_i32_debug(&mut self, n: i32) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_i64_debug(&mut self, n: i64) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_i128_debug(&mut self, n: i128) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

source

pub const fn write_isize_debug(&mut self, n: isize) -> Result<(), Error>

Writes n with debug formatting.

For an example, you can look at the one for the write_u8_debug method.

Trait Implementations§

source§

impl WriteMarker for Formatter<'_>

§

type Kind = IsNotAStrWriter

Whether this is a StrWriter or not, this can be either of IsAStrWriter or IsNotAStrWriter
§

type This = Formatter<'_>

The type after dereferencing, implemented as type This = Self; for all non-reference types

Auto Trait Implementations§

§

impl<'w> RefUnwindSafe for Formatter<'w>

§

impl<'w> Send for Formatter<'w>

§

impl<'w> Sync for Formatter<'w>

§

impl<'w> Unpin for Formatter<'w>

§

impl<'w> !UnwindSafe for Formatter<'w>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.