diff --git a/Cargo.toml b/Cargo.toml index f111cbf..a46bee7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "leftpad" -version = "0.1.0" +version = "0.2.0" authors = ["Hubert Figuière "] license = "BSD-2-Clause" description = "Pad a string to the left" diff --git a/NEWS b/NEWS new file mode 100644 index 0000000..5a053c0 --- /dev/null +++ b/NEWS @@ -0,0 +1,5 @@ +0.2.0 +- actually implement the proper behaviour + +0.1.0 +- first release. diff --git a/src/lib.rs b/src/lib.rs index 045a406..fed8e10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,19 +2,24 @@ -/// pad a string to the left with ``pad`` spaces -pub fn left_pad(s: &str, pad: u32) -> String +/// pad a string to the left to ``pad`` length with spaces +/// If str.len() is less than pad, then the string is returned verbatim +pub fn left_pad(s: &str, pad: usize) -> String { left_pad_char(s, pad, ' ') } -/// pad a string to the left with ``pad`` ``padchar`` -pub fn left_pad_char(s: &str, pad: u32, padchar: char) -> String +/// pad a string to the left to ``pad`` length with ``padchar`` +/// If str.len() is less than pad, then the string is returned verbatim +pub fn left_pad_char(s: &str, pad: usize, padchar: char) -> String { let mut out = String::new(); - for _ in 0..pad { - out.push(padchar); + let len = s.len(); + if pad > len { + for _ in 0..pad-len { + out.push(padchar); + } } out.push_str(s); @@ -26,9 +31,10 @@ pub fn left_pad_char(s: &str, pad: u32, padchar: char) -> String fn pad_test() { assert_eq!(left_pad("foo", 0), "foo"); + assert_eq!(left_pad("foo", 2), "foo"); assert_eq!(left_pad_char("bar", 0, 'Y'), "bar"); - assert_eq!(left_pad("foo", 2), " foo"); - assert_eq!(left_pad_char("foo", 2, 'X'), "XXfoo"); - assert_eq!(left_pad_char("bar", 5, '-'), "-----bar"); + assert_eq!(left_pad("foo", 5), " foo"); + assert_eq!(left_pad_char("foo", 7, 'X'), "XXXXfoo"); + assert_eq!(left_pad_char("bar", 5, '-'), "--bar"); }