[][src]Struct const_format::fmt::Formatter

pub struct Formatter<'w> { /* fields omitted */ }

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

impl<'w> Formatter<'w>[src]

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

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");

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

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");

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

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");

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

Construct a Formatterfrom a byte slice.

Example

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

pub const fn flags(&self) -> FormattingFlags[src]

Gets the formatting flags associated with this Formatter.

pub const fn margin(&self) -> usize[src]

Gets how much indentation a data structure is printed with.

impl<'w> Formatter<'w>[src]

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

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

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

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);

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

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

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

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

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

For debug writing a list/array.

Examples

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

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

For debug writing a set.

Examples

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

impl<'_> Formatter<'_>[src]

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

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");

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

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");

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

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");

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

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");

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

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");

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

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""#);

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

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""#);

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

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""#);

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

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""#);

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

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");

impl<'_> Formatter<'_>[src]

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

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

Writes n with display formatting

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

impl<'_> Formatter<'_>[src]

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

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_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_binary()),      "0b111111");

impl<'_> Formatter<'_>[src]

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

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

Writes n with debug formatting.

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

Trait Implementations

impl<'_> WriteMarker for Formatter<'_>[src]

type Kind = IsNotAStrWriter

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

type This = Self

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

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

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.