about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMara Bos <m-ou.se@m-ou.se>2020-07-04 17:59:37 +0200
committerMara Bos <m-ou.se@m-ou.se>2020-07-17 15:35:58 +0200
commite73a23fa969abd6fcf4ded3ad866fe1164e1268b (patch)
tree017818c3fb2c575a9e1d8906cf84b1e2531b0599
parentc2dbebd3d4ad21e80ef4e7535dd1e868aaad7e50 (diff)
downloadrust-e73a23fa969abd6fcf4ded3ad866fe1164e1268b.tar.gz
rust-e73a23fa969abd6fcf4ded3ad866fe1164e1268b.zip
Add Arguments::as_str().
-rw-r--r--src/libcore/fmt/mod.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs
index 9c5dbb5e6f3..449d8302d73 100644
--- a/src/libcore/fmt/mod.rs
+++ b/src/libcore/fmt/mod.rs
@@ -409,6 +409,41 @@ pub struct Arguments<'a> {
     args: &'a [ArgumentV1<'a>],
 }
 
+impl<'a> Arguments<'a> {
+    /// Get the formatted string, if it has no arguments to be formatted.
+    ///
+    /// This can be used to avoid allocations in the most trivial case.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// #![feature(fmt_as_str)]
+    ///
+    /// use core::fmt::Arguments;
+    ///
+    /// fn write_str(_: &str) { /* ... */ }
+    ///
+    /// fn write_fmt(args: &Arguments) {
+    ///     if let Some(s) = args.as_str() {
+    ///         write_str(s)
+    ///     } else {
+    ///         write_str(&args.to_string());
+    ///     }
+    /// }
+    /// ```
+    ///
+    /// ```rust
+    /// #![feature(fmt_as_str)]
+    ///
+    /// assert_eq!(format_args!("hello").as_str(), Some("hello"));
+    /// assert_eq!(format_args!("{}", 1).as_str(), None);
+    /// ```
+    #[unstable(feature = "fmt_as_str", issue = "none")]
+    pub fn as_str(&self) -> Option<&'a str> {
+        if self.args.is_empty() && self.pieces.len() == 1 { Some(self.pieces[0]) } else { None }
+    }
+}
+
 #[stable(feature = "rust1", since = "1.0.0")]
 impl Debug for Arguments<'_> {
     fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {