@@ -395,38 +395,14 @@ fn apply_modifiers(
395395 // Zero padding: sign first, then zeros (e.g., "-0022")
396396 let sign = result. chars ( ) . next ( ) . unwrap ( ) ;
397397 let rest = & result[ 1 ..] ;
398- let target_len = result. len ( ) . checked_add ( padding) . ok_or_else ( || {
399- FormatError :: FieldWidthTooLarge {
400- width : effective_width,
401- specifier : specifier. to_string ( ) ,
402- }
403- } ) ?;
404- let mut padded = String :: new ( ) ;
405- padded
406- . try_reserve ( target_len)
407- . map_err ( |_| FormatError :: FieldWidthTooLarge {
408- width : effective_width,
409- specifier : specifier. to_string ( ) ,
410- } ) ?;
398+ let mut padded = try_alloc_padded ( result. len ( ) , padding, effective_width, specifier) ?;
411399 padded. push ( sign) ;
412400 padded. extend ( std:: iter:: repeat_n ( '0' , padding) ) ;
413401 padded. push_str ( rest) ;
414402 result = padded;
415403 } else {
416404 // Default: pad on the left (e.g., " -22" or " 1999")
417- let target_len = result. len ( ) . checked_add ( padding) . ok_or_else ( || {
418- FormatError :: FieldWidthTooLarge {
419- width : effective_width,
420- specifier : specifier. to_string ( ) ,
421- }
422- } ) ?;
423- let mut padded = String :: new ( ) ;
424- padded
425- . try_reserve ( target_len)
426- . map_err ( |_| FormatError :: FieldWidthTooLarge {
427- width : effective_width,
428- specifier : specifier. to_string ( ) ,
429- } ) ?;
405+ let mut padded = try_alloc_padded ( result. len ( ) , padding, effective_width, specifier) ?;
430406 padded. extend ( std:: iter:: repeat_n ( pad_char, padding) ) ;
431407 padded. push_str ( & result) ;
432408 result = padded;
@@ -436,6 +412,30 @@ fn apply_modifiers(
436412 Ok ( result)
437413}
438414
415+ /// Allocate a `String` with enough capacity for `current_len + padding`,
416+ /// returning `FieldWidthTooLarge` on arithmetic overflow or allocation failure.
417+ fn try_alloc_padded (
418+ current_len : usize ,
419+ padding : usize ,
420+ width : usize ,
421+ specifier : & str ,
422+ ) -> Result < String , FormatError > {
423+ let target_len =
424+ current_len
425+ . checked_add ( padding)
426+ . ok_or_else ( || FormatError :: FieldWidthTooLarge {
427+ width,
428+ specifier : specifier. to_string ( ) ,
429+ } ) ?;
430+ let mut s = String :: new ( ) ;
431+ s. try_reserve ( target_len)
432+ . map_err ( |_| FormatError :: FieldWidthTooLarge {
433+ width,
434+ specifier : specifier. to_string ( ) ,
435+ } ) ?;
436+ Ok ( s)
437+ }
438+
439439#[ cfg( test) ]
440440mod tests {
441441 use super :: * ;
0 commit comments