Struct const_format::fmt::Formatter [−][src]
pub struct Formatter<'w> { /* fields omitted */ }
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:
-
From a pair of mutable reference to a
StrWriter
and aFormattingFlags
, with thefrom_sw
constructor. -
From a pair of
StrWriterMut
andFormattingFlags
, with thefrom_sw_mut
constructor. -
From a
ComputeStrLength
, by calling itsmake_formatter
method. This allows computing the length of formatted output without writing to anything. -
From a triple of
[u8]
andusize
mutable references, and aFormattingFlags
, with thefrom_custom_cleared
constructor, or thefrom_custom
constructor.
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
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
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");
pub const fn from_custom(
buffer: &'w mut [u8],
length: &'w mut usize,
flags: FormattingFlags
) -> Self
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");
pub const fn from_custom_cleared(
buffer: &'w mut [u8],
length: &'w mut usize,
flags: FormattingFlags
) -> Self
pub const fn from_custom_cleared(
buffer: &'w mut [u8],
length: &'w mut usize,
flags: FormattingFlags
) -> Self
Construct a Formatter
from a byte slice.
Example
For an example of using this method you can look at the type level docs
Gets the formatting flags associated with this Formatter
.
For borrowing this mutably in macros,just takes and returns a &mut Self
.
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);
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
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
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");
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");
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");
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");
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");
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");
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""#);
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""#);
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' '\'' "#);
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""#);
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""#);
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");
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
Writes n
with display formatting
For an example,
you can look at the one for the write_u8_display
method.
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");
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Writes n
with debug formatting.
For an example,
you can look at the one for the write_u8_debug
method.
Trait Implementations
type Kind = IsNotAStrWriter
type Kind = IsNotAStrWriter
Whether this is a StrWriter or not, this can be either of
IsAStrWriter
or IsNotAStrWriter
Read more