@@ -201,14 +201,22 @@ pub trait Write {
201
201
impl < W : Write + ?Sized > SpecWriteFmt for & mut W {
202
202
#[ inline]
203
203
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
+ }
205
209
}
206
210
}
207
211
208
212
impl < W : Write > SpecWriteFmt for & mut W {
209
213
#[ inline]
210
214
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
+ }
212
220
}
213
221
}
214
222
@@ -430,6 +438,14 @@ impl<'a> Arguments<'a> {
430
438
_ => None ,
431
439
}
432
440
}
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
+ }
433
449
}
434
450
435
451
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -1102,14 +1118,8 @@ pub trait UpperExp {
1102
1118
/// ```
1103
1119
///
1104
1120
/// [`write!`]: crate::write!
1105
- #[ inline]
1106
1121
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1107
1122
pub 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 {
1113
1123
let mut formatter = Formatter :: new ( output) ;
1114
1124
let mut idx = 0 ;
1115
1125
@@ -1588,8 +1598,9 @@ impl<'a> Formatter<'a> {
1588
1598
/// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1589
1599
/// ```
1590
1600
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1601
+ #[ inline]
1591
1602
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) }
1593
1604
}
1594
1605
1595
1606
/// Flags for formatting
@@ -2278,8 +2289,13 @@ impl Write for Formatter<'_> {
2278
2289
self . buf . write_char ( c)
2279
2290
}
2280
2291
2292
+ #[ inline]
2281
2293
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
+ }
2283
2299
}
2284
2300
}
2285
2301
0 commit comments