@@ -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" ) ]
@@ -1119,14 +1135,8 @@ pub trait UpperExp {
1119
1135
/// ```
1120
1136
///
1121
1137
/// [`write!`]: crate::write!
1122
- #[ inline]
1123
1138
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1124
1139
pub fn write ( output : & mut dyn Write , args : Arguments < ' _ > ) -> Result {
1125
- if let Some ( s) = args. as_str ( ) { output. write_str ( s) } else { write_internal ( output, args) }
1126
- }
1127
-
1128
- /// Actual implementation of the [`write()`], but without the simple string optimization.
1129
- fn write_internal ( output : & mut dyn Write , args : Arguments < ' _ > ) -> Result {
1130
1140
let mut formatter = Formatter :: new ( output) ;
1131
1141
let mut idx = 0 ;
1132
1142
@@ -1605,8 +1615,9 @@ impl<'a> Formatter<'a> {
1605
1615
/// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
1606
1616
/// ```
1607
1617
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1618
+ #[ inline]
1608
1619
pub fn write_fmt ( & mut self , fmt : Arguments < ' _ > ) -> Result {
1609
- write ( self . buf , fmt)
1620
+ if let Some ( s ) = fmt . as_const_str ( ) { self . buf . write_str ( s ) } else { write ( self . buf , fmt) }
1610
1621
}
1611
1622
1612
1623
/// Flags for formatting
@@ -2295,8 +2306,13 @@ impl Write for Formatter<'_> {
2295
2306
self . buf . write_char ( c)
2296
2307
}
2297
2308
2309
+ #[ inline]
2298
2310
fn write_fmt ( & mut self , args : Arguments < ' _ > ) -> Result {
2299
- write ( self . buf , args)
2311
+ if let Some ( s) = args. as_const_str ( ) {
2312
+ self . buf . write_str ( s)
2313
+ } else {
2314
+ write ( self . buf , args)
2315
+ }
2300
2316
}
2301
2317
}
2302
2318
0 commit comments