22
33
44
5- /// pad a string to the left with ``pad`` spaces
6- pub fn left_pad ( s : & str , pad : u32 ) -> String
5+ /// pad a string to the left to ``pad`` length with spaces
6+ /// If str.len() is less than pad, then the string is returned verbatim
7+ pub fn left_pad ( s : & str , pad : usize ) -> String
78{
89 left_pad_char ( s, pad, ' ' )
910}
1011
11- /// pad a string to the left with ``pad`` ``padchar``
12- pub fn left_pad_char ( s : & str , pad : u32 , padchar : char ) -> String
12+ /// pad a string to the left to ``pad`` length with ``padchar``
13+ /// If str.len() is less than pad, then the string is returned verbatim
14+ pub fn left_pad_char ( s : & str , pad : usize , padchar : char ) -> String
1315{
1416 let mut out = String :: new ( ) ;
1517
16- for _ in 0 ..pad {
17- out. push ( padchar) ;
18+ let len = s. len ( ) ;
19+ if pad > len {
20+ for _ in 0 ..pad-len {
21+ out. push ( padchar) ;
22+ }
1823 }
1924 out. push_str ( s) ;
2025
@@ -26,9 +31,10 @@ pub fn left_pad_char(s: &str, pad: u32, padchar: char) -> String
2631fn pad_test ( ) {
2732
2833 assert_eq ! ( left_pad( "foo" , 0 ) , "foo" ) ;
34+ assert_eq ! ( left_pad( "foo" , 2 ) , "foo" ) ;
2935 assert_eq ! ( left_pad_char( "bar" , 0 , 'Y' ) , "bar" ) ;
30- assert_eq ! ( left_pad( "foo" , 2 ) , " foo" ) ;
31- assert_eq ! ( left_pad_char( "foo" , 2 , 'X' ) , "XXfoo " ) ;
32- assert_eq ! ( left_pad_char( "bar" , 5 , '-' ) , "----- bar" ) ;
36+ assert_eq ! ( left_pad( "foo" , 5 ) , " foo" ) ;
37+ assert_eq ! ( left_pad_char( "foo" , 7 , 'X' ) , "XXXXfoo " ) ;
38+ assert_eq ! ( left_pad_char( "bar" , 5 , '-' ) , "--bar" ) ;
3339}
3440
0 commit comments