@@ -324,7 +324,7 @@ impl<'a> Arguments<'a> {
324324 #[ doc( hidden) ]
325325 #[ inline]
326326 #[ unstable( feature = "fmt_internals" , reason = "internal to format_args!" , issue = "none" ) ]
327- pub fn new_v1 ( pieces : & ' a [ & ' a str ] , args : & ' a [ ArgumentV1 < ' a > ] ) -> Arguments < ' a > {
327+ pub fn new_v1 ( pieces : & ' a [ & ' static str ] , args : & ' a [ ArgumentV1 < ' a > ] ) -> Arguments < ' a > {
328328 Arguments { pieces, fmt : None , args }
329329 }
330330
@@ -338,7 +338,7 @@ impl<'a> Arguments<'a> {
338338 #[ inline]
339339 #[ unstable( feature = "fmt_internals" , reason = "internal to format_args!" , issue = "none" ) ]
340340 pub fn new_v1_formatted (
341- pieces : & ' a [ & ' a str ] ,
341+ pieces : & ' a [ & ' static str ] ,
342342 args : & ' a [ ArgumentV1 < ' a > ] ,
343343 fmt : & ' a [ rt:: v1:: Argument ] ,
344344 ) -> Arguments < ' a > {
@@ -399,7 +399,7 @@ impl<'a> Arguments<'a> {
399399#[ derive( Copy , Clone ) ]
400400pub struct Arguments < ' a > {
401401 // Format string pieces to print.
402- pieces : & ' a [ & ' a str ] ,
402+ pieces : & ' a [ & ' static str ] ,
403403
404404 // Placeholder specs, or `None` if all specs are default (as in "{}{}").
405405 fmt : Option < & ' a [ rt:: v1:: Argument ] > ,
@@ -409,6 +409,47 @@ 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!("").as_str(), Some(""));
440+ /// assert_eq!(format_args!("{}", 1).as_str(), None);
441+ /// ```
442+ #[ unstable( feature = "fmt_as_str" , issue = "74442" ) ]
443+ #[ inline]
444+ pub fn as_str ( & self ) -> Option < & ' static str > {
445+ match ( self . pieces , self . args ) {
446+ ( [ ] , [ ] ) => Some ( "" ) ,
447+ ( [ s] , [ ] ) => Some ( s) ,
448+ _ => None ,
449+ }
450+ }
451+ }
452+
412453#[ stable( feature = "rust1" , since = "1.0.0" ) ]
413454impl Debug for Arguments < ' _ > {
414455 fn fmt ( & self , fmt : & mut Formatter < ' _ > ) -> Result {
0 commit comments