| 1 |
//! A try_format! macro replacing format! |
| 2 |
use super::FallibleVec; |
| 3 |
use crate::TryReserveError; |
| 4 |
use alloc::fmt::{Arguments, Write}; |
| 5 |
use alloc::string::String; |
| 6 |
|
| 7 |
/// Take a max capacity a try allocating a string with it. |
| 8 |
/// |
| 9 |
/// # Warning: |
| 10 |
/// |
| 11 |
/// the max capacity must be > to the formating of the |
| 12 |
/// arguments. If writing the argument on the string exceed the |
| 13 |
/// capacity, no error is return and an allocation can occurs which |
| 14 |
/// can lead to a panic |
| 15 |
pub fn try_format(max_capacity: usize, args: Arguments<'_>) -> Result<String, TryReserveError> { |
| 16 |
let v = FallibleVec::try_with_capacity(max_capacity)?; |
| 17 |
let mut s = String::from_utf8(v).expect("wtf an empty vec should be valid utf8"); |
| 18 |
s.write_fmt(args) |
| 19 |
.expect("a formatting trait implementation returned an error"); |
| 20 |
Ok(s) |
| 21 |
} |
| 22 |
|
| 23 |
#[macro_export] |
| 24 |
/// Take a max capacity a try allocating a string with it. |
| 25 |
/// |
| 26 |
/// # Warning: |
| 27 |
/// |
| 28 |
/// the max capacity must be > to the formating of the |
| 29 |
/// arguments. If writing the argument on the string exceed the |
| 30 |
/// capacity, no error is return and an allocation can occurs which |
| 31 |
/// can lead to a panic |
| 32 |
macro_rules! tryformat { |
| 33 |
($max_capacity:tt, $($arg:tt)*) => ( |
| 34 |
$crate::format::try_format($max_capacity, format_args!($($arg)*)) |
| 35 |
) |
| 36 |
} |
| 37 |
|
| 38 |
#[cfg(test)] |
| 39 |
mod tests { |
| 40 |
#[test] |
| 41 |
fn format() { |
| 42 |
assert_eq!(tryformat!(1, "1").unwrap(), format!("1")); |
| 43 |
assert_eq!(tryformat!(1, "{}", 1).unwrap(), format!("{}", 1)); |
| 44 |
assert_eq!(tryformat!(3, "{}", 123).unwrap(), format!("{}", 123)); |
| 45 |
} |
| 46 |
} |