pub struct StrWriterMut<'w, E = Utf8Encoding> { /* private fields */ }
Available on crate feature fmt only.
Expand description

For writing a formatted string into a [u8].

Construction

This type can be constructed in these ways:

Relation to Formatter

This is the type that Formatter uses to write formatted text to a slice, sharing all the write_* methods, the difference is that this doesn’t store FormattingFlags, so you must pass them to the write_*_debug methods.

Errors

Every single write_* method returns an Error::NotEnoughSpace if there is not enough space to write the argument, leaving the string itself unmodified.

Encoding type parameter

The E type parameter represents the encoding of the buffer that this StrWriterMut writes into, currently only Utf8Encoding and NoEncoding are supported.

Example

This example demonstrates how you can write a formatted string to a &mut [u8], using a StrWriterMut.

#![feature(const_mut_refs)]

use const_format::{Error, StrWriterMut, try_, writec};

const fn format_number(number: u32,slice: &mut [u8]) -> Result<usize, Error> {
    let mut len = 0;
    let mut writer = StrWriterMut::from_custom_cleared(slice, &mut len);
     
    try_!(writec!(writer, "{0} in binary is {0:#b}", number));

    Ok(len)
}

let mut slice = [0; 32];

let len = format_number(100, &mut slice)?;

assert_eq!(&slice[..len], "100 in binary is 0b1100100".as_bytes());

Implementations

Constructs a StrWriterMut from a mutable reference to a StrWriter

Example
use const_format::{StrWriter, StrWriterMut};

let buffer: &mut StrWriter = &mut StrWriter::new([0; 128]);
{
    let mut writer = StrWriterMut::new(buffer);

    let _ = writer.write_str("Number: ");
    let _ = writer.write_u8_display(1);
}
assert_eq!(buffer.as_str(), "Number: 1");

Construct a StrWriterMut from length and byte slice mutable references.

If length > buffer.len() is passed, it’s simply assigned the length of the buffer.

Example
use const_format::StrWriterMut;

let mut len = 6;
let mut buffer = *b"Hello,       ";

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

writer.write_str(" world!")?;

assert_eq!(writer.as_bytes(), b"Hello, world!");
assert_eq!(buffer, "Hello, world!".as_bytes());
assert_eq!(len, "Hello, world!".len());

Construct a StrWriterMut from length and byte slice mutable references, truncating the length to 0.

Using this instead of from_custom allows safely casting this to a &str with as_str_alt/as_str

Example
use const_format::StrWriterMut;

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

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

writer.write_str("Hello, world!")?;

assert_eq!(writer.as_str(), "Hello, world!");
assert_eq!(buffer, "Hello, world!".as_bytes());
assert_eq!(len, "Hello, world!".len());

Accesses the underlying buffer immutably.

Example
use const_format::{StrWriter, StrWriterMut};

let mut buffer = StrWriter::new([0; 7]);
let mut writer = StrWriterMut::new(&mut buffer);
assert_eq!(writer.buffer(), &[0; 7]);

writer.write_str("foo")?;
assert_eq!(writer.buffer(), b"foo\0\0\0\0");

writer.write_str("bar")?;
assert_eq!(writer.buffer(), b"foobar\0");

The byte length of the string this is writing.

Example
use const_format::{StrWriter, StrWriterMut};

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

assert_eq!(writer.len(), 0);

writer.write_str("foo")?;
assert_eq!(writer.len(), 3);

writer.write_str("bar")?;
assert_eq!(writer.len(), 6);

Whether the string this is writing is empty.

Example
use const_format::{StrWriter, StrWriterMut};

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

assert!( writer.is_empty() );

writer.write_str("foo")?;
assert!( !writer.is_empty() );

The maximum byte length of the formatted text for this StrWriterMut.

Example
use const_format::{Error, StrWriter, StrWriterMut};

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

assert_eq!(writer.capacity(), 64);

writer.write_ascii_repeated(b'A', 64)?;
assert_eq!(writer.capacity(), 64);

assert_eq!(writer.write_str("-").unwrap_err(), Error::NotEnoughSpace);
assert_eq!(writer.capacity(), 64);

Checks how many more bytes can be written.

Example
use const_format::{Error, StrWriter, StrWriterMut};

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

assert_eq!(writer.remaining_capacity(), 64);

writer.write_str("foo")?;
assert_eq!(writer.remaining_capacity(), 61);

writer.write_ascii_repeated(b'a', 61)?;
assert_eq!(writer.remaining_capacity(), 0);

assert_eq!(writer.write_str(" ").unwrap_err(), Error::NotEnoughSpace);

Truncates this StrWriterMut to length.

If length is greater than the current length, this does nothing.

Errors

Returns an Error::NotOnCharBoundary if length is not on a char boundary.

Example
use const_format::{Error, StrWriter, StrWriterMut};

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

writer.write_str("foo bâr baz");
assert_eq!(writer.as_str(), "foo bâr baz");

assert_eq!(writer.truncate(6).unwrap_err(), Error::NotOnCharBoundary);

writer.truncate(3)?;
assert_eq!(writer.as_str(), "foo");

writer.write_str("ooooooo");
assert_eq!(writer.as_str(), "fooooooooo");

Truncates this StrWriterMut<'w, NoEncoding> to length.

If length is greater than the current length, this does nothing.

Example
use const_format::{Error, StrWriter, StrWriterMut};

let mut buffer = [0; 32];
let mut len = 0;
let mut writer = StrWriterMut::from_custom(&mut buffer, &mut len);

writer.write_str("foo bar baz");
assert_eq!(writer.as_bytes(), b"foo bar baz");

// Truncating to anything larger than the length is a no-op.
writer.truncate(usize::MAX / 2);
assert_eq!(writer.as_bytes(), b"foo bar baz");

writer.truncate(3);
assert_eq!(writer.as_bytes(), b"foo");

writer.write_str("ooooooo");
assert_eq!(writer.as_bytes(), b"fooooooooo");

Truncates this StrWriterMut to length 0.

Example
use const_format::{Error, StrWriter, StrWriterMut};

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

writer.write_str("foo")?;
assert_eq!(writer.as_str(), "foo");

writer.clear();
assert_eq!(writer.as_str(), "");
assert!(writer.is_empty());

writer.write_str("bar");
assert_eq!(writer.as_str(), "bar");

Gets the written part of this StrWriterMut as a &[u8]

The slice is guaranteed to be valid utf8, so this is mostly for convenience.

Runtime

If the “constant_time_as_str” feature is disabled, this takes time proportional to self.capacity() - self.len().

If the “constant_time_as_str” feature is enabled, it takes constant time to run, but uses a few additional nightly features.

Example
#![feature(const_mut_refs)]

use const_format::{StrWriter, StrWriterMut};

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

writer.write_str("Hello, World!");

assert_eq!(writer.as_bytes_alt(), "Hello, World!".as_bytes());

Gets the written part of this StrWriterMut as a &str

Runtime

If the “constant_time_as_str” feature is disabled, this takes time proportional to self.capacity() - self.len().

If the “constant_time_as_str” feature is enabled, it takes constant time to run, but uses a few additional nightly features.

Example
#![feature(const_mut_refs)]

use const_format::{StrWriter, StrWriterMut};
use const_format::{unwrap, writec};


const CAP: usize = 128;

const __STR: &StrWriter = &{
    let mut buffer =  StrWriter::new([0; CAP]);
    let mut writer = StrWriterMut::new(&mut buffer);

    // Writing the array with debug formatting, and the integers with hexadecimal formatting.
    unwrap!(writec!(writer, "{:x}", [3u32, 5, 8, 13, 21, 34]));

    buffer
};

const STR: &str = __STR.as_str_alt();

fn main() {
    assert_eq!(STR, "[3, 5, 8, D, 15, 22]");
}

Gets the written part of this StrWriterMut as a &str

Constness

This can be called in const contexts by enabling the “constant_time_as_str” feature, which requires nightly Rust versions after 2021-07-15.

Alternative

You can also use the as_str_alt method, which is always available, but takes linear time to run when the “constant_time_as_str” feature is disabled.

Example
#![feature(const_mut_refs)]

use const_format::{StrWriter, StrWriterMut};

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

writer.write_str("Hello, how are you?");

assert_eq!(writer.as_str(), "Hello, how are you?");

Gets the written part of this StrWriterMut as a &[u8]

The slice is guaranteed to be valid utf8, so this is mostly for convenience.

Constness

This can be called in const contexts by enabling the “constant_time_as_str” feature, which requires nightly Rust versions after 2021-07-15.

Example
#![feature(const_mut_refs)]

use const_format::{StrWriter, StrWriterMut};

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

writer.write_str("Hello, World!");

assert_eq!(writer.as_bytes_alt(), "Hello, World!".as_bytes());

Constructs a Formatter that writes into this StrWriterMut, which can be passed to debug and display formatting methods.

Example
#![feature(const_mut_refs)]

use const_format::{Error, Formatter, FormattingFlags, StrWriter, StrWriterMut};
use const_format::call_debug_fmt;

use std::ops::Range;

const fn range_debug_fmt(
    slice: &[Range<usize>],
    f: &mut Formatter<'_>
) -> Result<(), Error> {
    // We need this macro to debug format arrays of non-primitive types
    // Also, it implicitly returns a `const_format::Error` on error.
    call_debug_fmt!(array, slice, f);
    Ok(())
}

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

range_debug_fmt(
    &[0..14, 14..31, 31..48],
    &mut writer.make_formatter(FormattingFlags::new().set_binary())
)?;
    
assert_eq!(writer.as_str(), "[0..1110, 1110..11111, 11111..110000]");

For borrowing this mutably in macros, without getting nested mutable references.

For passing a reborrow of this StrWriterMut into functions, without this you’d need to pass a mutable reference instead.

Example
#![feature(const_mut_refs)]

use const_format::{Error, FormattingFlags, StrWriter, StrWriterMut, call_debug_fmt};

use std::ops::Range;

const fn range_debug_fmt(
    slice: &[[u32; 2]],
    mut writer: StrWriterMut<'_>
) -> Result<(), Error> {
    let mut formatter = writer.make_formatter(FormattingFlags::new().set_binary());

    // We need this macro to debug format arrays of non-primitive types
    // Also, it implicitly returns a `const_format::Error` on error.
    call_debug_fmt!(array, slice, formatter);
    Ok(())
}

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

range_debug_fmt(&[[3, 5], [8, 13]], writer.reborrow())?;
    
assert_eq!(writer.as_str(), "[[11, 101], [1000, 1101]]");

Writes a subslice of s with Display formatting.

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

Additional Errors

This method returns Error::NotOnCharBoundary if the range is not on a character boundary.

Out of bounds range bounds are treated as being at s.len(), this only returns an error on an in-bounds index that is not on a character boundary.

Example
use const_format::{FormattingFlags, StrWriterMut};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes s with Display formatting.

Example

use const_format::{FormattingFlags, StrWriterMut};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes character with Display formatting

Example

use const_format::StrWriterMut;

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

let _ = writer.write_char('3');
let _ = writer.write_char('5');
let _ = writer.write_char('8');

assert_eq!(writer.as_str(), "358");

Writes a subslice of ascii with Display formatting.

Out of bounds range bounds are treated as being at s.len().

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

Example

use const_format::{FormattingFlags, StrWriterMut, ascii_str};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes ascii with Display formatting.

Example

use const_format::{FormattingFlags, StrWriterMut, ascii_str};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes an ascii character, repeated times.

Example

use const_format::{FormattingFlags, StrWriterMut};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Debug-formatted string writing

Writes a subslice of s with Debug-like formatting.

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

Additional Errors

This method returns Error::NotOnCharBoundary if the range is not on a character boundary.

Out of bounds range bounds are treated as being at s.len(), this only returns an error on an in-bounds index that is not on a character boundary.

Example

use const_format::{FormattingFlags, StrWriterMut};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes s with Debug-like formatting.

Example

use const_format::{FormattingFlags, StrWriterMut};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes character with Debug formatting.

Example

use const_format::StrWriterMut;

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes a subslice of ascii with Debug-like formatting.

Out of bounds range bounds are treated as being at s.len().

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

Example

use const_format::{FormattingFlags, StrWriterMut, ascii_str};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Writes ascii with Debug-like formatting.

Example

use const_format::{FormattingFlags, StrWriterMut, ascii_str};

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

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

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

Write number with display formatting.

Example

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

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

let _ = writer.write_u8_display(137);

assert_eq!(writer.as_str(), "137");

Writes number with debug formatting.

Example
#![feature(const_mut_refs)]

use const_format::{FormattingFlags, StrWriterMut};

const fn debug_fmt<'a>(
    writer: &'a mut StrWriterMut<'_>,
    flag: FormattingFlags
) -> &'a str {
    writer.clear();
    let _ = writer.write_u8_debug(63, flag);
    writer.as_str_alt()
}

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

let mut len = 0;
let mut buffer = [0; 64];
let mut writer = StrWriterMut::from_custom_cleared(&mut buffer, &mut len);

assert_eq!(debug_fmt(&mut writer, reg_flag),                   "63"     );
assert_eq!(debug_fmt(&mut writer, reg_flag.set_hexadecimal()), "3F"     );
assert_eq!(debug_fmt(&mut writer, reg_flag.set_binary()),      "111111" );
assert_eq!(debug_fmt(&mut writer, alt_flag),                   "63"     );
assert_eq!(debug_fmt(&mut writer, alt_flag.set_hexadecimal()), "0x3F"   );
assert_eq!(debug_fmt(&mut writer, alt_flag.set_binary()),      "0b111111");

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Writes number with display formatting

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

Writes number with debug formatting.

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

Trait Implementations

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

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

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.