Skip to content

rust: alloc: implement try_format! macro #478

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: rust
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion rust/alloc/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ pub use core::fmt::{LowerExp, UpperExp};
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::fmt::{LowerHex, Pointer, UpperHex};

#[cfg(not(no_global_oom_handling))]
use crate::collections::TryReserveError;
use crate::string;

/// The `format` function takes an [`Arguments`] struct and returns the resulting
Expand Down Expand Up @@ -585,3 +585,50 @@ pub fn format(args: Arguments<'_>) -> string::String {
output.write_fmt(args).expect("a formatting trait implementation returned an error");
output
}

/// The `try_format` function takes an [`Arguments`] struct and returns the
/// resulting formatted string if all memory allocations during formatting
/// were succesful.
///
/// The [`Arguments`] instance can be created with the [`format_args!`] macro.
///
/// # Errors
///
/// If the capacity of overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Panics
///
/// Panics if a formatting trait implementation returns an error.
/// This indicates an incorrect implementation
/// since `fmt::Write for String` never returns an error itself.
/// Never panics on memory allocation failure.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::fmt;
///
/// let s = fmt::try_format(format_args!("Hello, {}!", "world")).unwrap();
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// Please note that using [`try_format!`] might be preferable.
/// Example:
///
/// ```
/// let s = try_format!("Hello, {}!", "world").unwrap();
/// assert_eq!(s, "Hello, world!");
/// ```
///
/// [`format_args!`]: core::format_args
/// [`try_format!`]: crate::try_format
#[stable(feature = "kernel", since = "1.0.0")]
pub fn try_format(args: Arguments<'_>) -> core::result::Result<string::String, TryReserveError> {
let capacity = args.estimated_capacity();
let mut writer = string::StringWriter::try_with_capacity(capacity)?;
writer.write_fmt(args).expect("a formatting trait implementation returned an error");
writer.into_string()
}
35 changes: 35 additions & 0 deletions rust/alloc/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,41 @@ macro_rules! format {
}}
}

/// Tries to create a `String` using interpolation of runtime expressions.
///
/// The `try_format!` is an equivalent of [`format!`] macro, that will never
/// panic on memory allocation failure. See [`format!`] for functionality details.
///
/// [`format!`]: crate::format
///
/// # Errors
///
/// If the capacity overflows, or the allocator reports a failure, then an error
/// is returned.
///
/// # Panics
///
/// `try_format!` panics if a formatting trait implementation returns an error.
/// This indicates an incorrect implementation
/// since `fmt::Write for String` never returns an error itself.
/// Never panics on memory allocation failure.
///
/// # Examples
///
/// ```
/// try_format!("test").unwrap();
/// try_format!("hello {}", "world!").unwrap();
/// try_format!("x = {}, y = {y}", 10, y = 30).unwrap();
/// ```
#[macro_export]
#[stable(feature = "kernel", since = "1.0.0")]
macro_rules! try_format {
($($arg:tt)*) => {{
let res = $crate::fmt::try_format($crate::__export::format_args!($($arg)*));
res
}}
}

/// Force AST node to an expression to improve diagnostics in pattern position.
#[doc(hidden)]
#[macro_export]
Expand Down
Loading