@@ -201,14 +201,22 @@ pub trait Write {
201201 impl < W : Write + ?Sized > SpecWriteFmt for & mut W {
202202 #[ inline]
203203 default fn spec_write_fmt ( mut self , args : Arguments < ' _ > ) -> Result {
204- write ( & mut self , args)
204+ if let Some ( s) = args. as_const_str ( ) {
205+ self . write_str ( s)
206+ } else {
207+ write ( & mut self , args)
208+ }
205209 }
206210 }
207211
208212 impl < W : Write > SpecWriteFmt for & mut W {
209213 #[ inline]
210214 fn spec_write_fmt ( self , args : Arguments < ' _ > ) -> Result {
211- write ( self , args)
215+ if let Some ( s) = args. as_const_str ( ) {
216+ self . write_str ( s)
217+ } else {
218+ write ( self , args)
219+ }
212220 }
213221 }
214222
@@ -430,6 +438,14 @@ impl<'a> Arguments<'a> {
430438 _ => None ,
431439 }
432440 }
441+
442+ /// Same as [`Arguments::as_str`], but will only return `Some(s)` if it can be determined at compile time.
443+ #[ must_use]
444+ #[ inline]
445+ fn as_const_str ( & self ) -> Option < & ' static str > {
446+ let s = self . as_str ( ) ;
447+ if core:: intrinsics:: is_val_statically_known ( s. is_some ( ) ) { s } else { None }
448+ }
433449}
434450
435451#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -1102,14 +1118,8 @@ pub trait UpperExp {
11021118/// ```
11031119///
11041120/// [`write!`]: crate::write!
1105- #[ inline]
11061121#[ stable( feature = "rust1" , since = "1.0.0" ) ]
11071122pub fn write ( output : & mut dyn Write , args : Arguments < ' _ > ) -> Result {
1108- if let Some ( s) = args. as_str ( ) { output. write_str ( s) } else { write_internal ( output, args) }
1109- }
1110-
1111- /// Actual implementation of the [`write()`], but without the simple string optimization.
1112- fn write_internal ( output : & mut dyn Write , args : Arguments < ' _ > ) -> Result {
11131123 let mut formatter = Formatter :: new ( output) ;
11141124 let mut idx = 0 ;
11151125
@@ -1588,8 +1598,9 @@ impl<'a> Formatter<'a> {
15881598 /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
15891599 /// ```
15901600 #[ stable( feature = "rust1" , since = "1.0.0" ) ]
1601+ #[ inline]
15911602 pub fn write_fmt ( & mut self , fmt : Arguments < ' _ > ) -> Result {
1592- write ( self . buf , fmt)
1603+ if let Some ( s ) = fmt . as_const_str ( ) { self . buf . write_str ( s ) } else { write ( self . buf , fmt) }
15931604 }
15941605
15951606 /// Flags for formatting
@@ -2278,8 +2289,13 @@ impl Write for Formatter<'_> {
22782289 self . buf . write_char ( c)
22792290 }
22802291
2292+ #[ inline]
22812293 fn write_fmt ( & mut self , args : Arguments < ' _ > ) -> Result {
2282- write ( self . buf , args)
2294+ if let Some ( s) = args. as_const_str ( ) {
2295+ self . buf . write_str ( s)
2296+ } else {
2297+ write ( self . buf , args)
2298+ }
22832299 }
22842300}
22852301
0 commit comments