Skip to content

Commit e73a23f

Browse files
committed
Add Arguments::as_str().
1 parent c2dbebd commit e73a23f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/libcore/fmt/mod.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,41 @@ pub struct Arguments<'a> {
409409
args: &'a [ArgumentV1<'a>],
410410
}
411411

412+
impl<'a> Arguments<'a> {
413+
/// Get the formatted string, if it has no arguments to be formatted.
414+
///
415+
/// This can be used to avoid allocations in the most trivial case.
416+
///
417+
/// # Examples
418+
///
419+
/// ```rust
420+
/// #![feature(fmt_as_str)]
421+
///
422+
/// use core::fmt::Arguments;
423+
///
424+
/// fn write_str(_: &str) { /* ... */ }
425+
///
426+
/// fn write_fmt(args: &Arguments) {
427+
/// if let Some(s) = args.as_str() {
428+
/// write_str(s)
429+
/// } else {
430+
/// write_str(&args.to_string());
431+
/// }
432+
/// }
433+
/// ```
434+
///
435+
/// ```rust
436+
/// #![feature(fmt_as_str)]
437+
///
438+
/// assert_eq!(format_args!("hello").as_str(), Some("hello"));
439+
/// assert_eq!(format_args!("{}", 1).as_str(), None);
440+
/// ```
441+
#[unstable(feature = "fmt_as_str", issue = "none")]
442+
pub fn as_str(&self) -> Option<&'a str> {
443+
if self.args.is_empty() && self.pieces.len() == 1 { Some(self.pieces[0]) } else { None }
444+
}
445+
}
446+
412447
#[stable(feature = "rust1", since = "1.0.0")]
413448
impl Debug for Arguments<'_> {
414449
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {

0 commit comments

Comments
 (0)