File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff 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" ) ]
413448impl Debug for Arguments < ' _ > {
414449 fn fmt ( & self , fmt : & mut Formatter < ' _ > ) -> Result {
You can’t perform that action at this time.
0 commit comments