@@ -324,7 +324,7 @@ impl<'a> Arguments<'a> {
324
324
#[ doc( hidden) ]
325
325
#[ inline]
326
326
#[ 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 > {
328
328
Arguments { pieces, fmt : None , args }
329
329
}
330
330
@@ -338,7 +338,7 @@ impl<'a> Arguments<'a> {
338
338
#[ inline]
339
339
#[ unstable( feature = "fmt_internals" , reason = "internal to format_args!" , issue = "none" ) ]
340
340
pub fn new_v1_formatted (
341
- pieces : & ' a [ & ' a str ] ,
341
+ pieces : & ' a [ & ' static str ] ,
342
342
args : & ' a [ ArgumentV1 < ' a > ] ,
343
343
fmt : & ' a [ rt:: v1:: Argument ] ,
344
344
) -> Arguments < ' a > {
@@ -399,7 +399,7 @@ impl<'a> Arguments<'a> {
399
399
#[ derive( Copy , Clone ) ]
400
400
pub struct Arguments < ' a > {
401
401
// Format string pieces to print.
402
- pieces : & ' a [ & ' a str ] ,
402
+ pieces : & ' a [ & ' static str ] ,
403
403
404
404
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
405
405
fmt : Option < & ' a [ rt:: v1:: Argument ] > ,
@@ -409,6 +409,47 @@ pub struct Arguments<'a> {
409
409
args : & ' a [ ArgumentV1 < ' a > ] ,
410
410
}
411
411
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
+
412
453
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
413
454
impl Debug for Arguments < ' _ > {
414
455
fn fmt ( & self , fmt : & mut Formatter < ' _ > ) -> Result {
0 commit comments