File tree 1 file changed +13
-21
lines changed
1 file changed +13
-21
lines changed Original file line number Diff line number Diff line change @@ -486,31 +486,23 @@ pub fn capitalize(s: impl ToString) -> Result<impl fmt::Display, Infallible> {
486
486
487
487
/// Centers the value in a field of a given width
488
488
#[ inline]
489
- pub fn center ( src : impl ToString , dst_len : usize ) -> Result < impl fmt:: Display , Infallible > {
490
- fn center ( src : String , dst_len : usize ) -> Result < String , Infallible > {
491
- let len = src. len ( ) ;
492
- if dst_len <= len || dst_len >= MAX_LEN {
493
- Ok ( src)
494
- } else {
495
- let diff = dst_len - len;
496
- let mid = diff / 2 ;
497
- let r = diff % 2 ;
498
- let mut buf = String :: with_capacity ( dst_len) ;
499
-
500
- for _ in 0 ..mid {
501
- buf. push ( ' ' ) ;
502
- }
503
-
504
- buf. push_str ( & src) ;
489
+ pub fn center ( src : impl fmt:: Display , width : usize ) -> Result < impl fmt:: Display , Infallible > {
490
+ Ok ( Center { src, width } )
491
+ }
505
492
506
- for _ in 0 ..mid + r {
507
- buf. push ( ' ' ) ;
508
- }
493
+ struct Center < T > {
494
+ src : T ,
495
+ width : usize ,
496
+ }
509
497
510
- Ok ( buf)
498
+ impl < T : fmt:: Display > fmt:: Display for Center < T > {
499
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
500
+ if self . width < MAX_LEN {
501
+ write ! ( f, "{: ^1$}" , self . src, self . width)
502
+ } else {
503
+ write ! ( f, "{}" , self . src)
511
504
}
512
505
}
513
- center ( src. to_string ( ) , dst_len)
514
506
}
515
507
516
508
/// Count the words in that string.
You can’t perform that action at this time.
0 commit comments