[][src]Struct const_format::fmt::ComputeStrLength

pub struct ComputeStrLength { /* fields omitted */ }

For computing how long a formatted string would be.

This is what the formatc macro uses to precalculate the length of its returned &str.

Example

#![feature(const_mut_refs)]

use const_format::fmt::{ComputeStrLength, Error, Formatter, FormattingFlags, StrWriter};
use const_format::{try_, writec, unwrap};

const fn write_sum(mut f: Formatter<'_>) -> Result<(), Error> {
    let l = 7u8;
    let r = 8u8;
    writec!(f, "{} + {} = {}", l, r, l + r)
}

// This is a const fn because mutable references can't be used in const initializers.
const fn len() -> usize {
    let mut computer = ComputeStrLength::new();
    unwrap!(write_sum(computer.make_formatter(FormattingFlags::NEW)));
    computer.len()
}
const LEN: usize = len();

// The type annotation coerces a `&mut StrWriter<[u8; LEN]>`
// to a `&mut StrWriter<[u8]>` (the type parameter defaults to `[u8]`)
let writer: &mut StrWriter = &mut StrWriter::new([0; LEN]);

write_sum(writer.make_formatter(FormattingFlags::NEW)).unwrap();

assert_eq!(writer.as_str(), "7 + 8 = 15");
assert_eq!(writer.len(), LEN);
assert_eq!(writer.capacity(), LEN);

Implementations

impl ComputeStrLength[src]

pub const fn new() -> Self[src]

Constructs a ComputeStrLength of length 0.

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

Constructs a Formatter, which instead of writing to a buffer it adds the computed length into this.

pub const fn add_len(&mut self, len: usize)[src]

Adds len to the calculated length.

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

The length of the string when formatted.

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

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

Auto Trait Implementations

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.