leftpad/
lib.rs

1
2
3
4
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
7pub fn left_pad(s: &str, pad: usize) -> String
8{
9    left_pad_char(s, pad, ' ')
10}
11
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
14pub fn left_pad_char(s: &str, pad: usize, padchar: char) -> String
15{
16    let mut out = String::new();
17
18    let len = s.len();
19    if pad > len {
20        for _ in 0..pad-len {
21            out.push(padchar);
22        }
23    }
24    out.push_str(s);
25
26    out
27}
28
29#[cfg(test)]
30#[test]
31fn pad_test() {
32
33    assert_eq!(left_pad("foo", 0), "foo");
34    assert_eq!(left_pad("foo", 2), "foo");
35    assert_eq!(left_pad_char("bar", 0, 'Y'), "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");
39}
40