leftpad_rs/
lib.rs

1//! Leftpad implementation in Rust.
2//!
3//! This is a Rust implementation of the famous Leftpad NPM package with `pad()` and `pad_char()`.
4//! Based on the Go implementation I wrote back in 2018.
5//!
6//! Examples:
7//! ```
8//!   use leftpad_rs::{pad,pad_char};
9//!
10//!   let r = pad("foo", 5);  // -> "  foo"
11//!
12//!   let s = pad_char("foo", 6, 'X');    // -> "XXXfoo"
13//! ```
14
15/// This module implements `pad` and `pad_char`.
16/// Left-pads the string with spaces.
17pub fn pad(s: &str, n: usize) -> String {
18    format!("{:>width$}", s, width = n)
19}
20
21/// Left-pads the string with the supplied character.
22pub fn pad_char(s: &str, n: usize, c: char) -> Result<String, &str> {
23    let l = s.len();
24
25    if n == 0 {
26        return Err("invalid size");
27    }
28    if n <= l {
29        return Ok(s.to_string());
30    }
31    let f = c.to_string().repeat(n - l);
32    Ok(format!("{}{}", f, s))
33}
34
35/// Useful alias
36pub fn pad_with(s: &str, n: usize, c: char) -> Result<String, &str> {
37    pad_char(s, n, c)
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    use rstest::rstest;
45
46    #[rstest]
47    #[case(2, "foo")]
48    #[case(3, "foo")]
49    #[case(4, " foo")]
50    #[case(5, "  foo")]
51    fn test_pad(#[case] n: usize, #[case] want: &str) {
52        assert_eq!(want, pad("foo", n));
53    }
54
55    #[test]
56    fn test_nopad() {
57        assert_ne!(pad("foo", 6), "foobar")
58    }
59
60    #[rstest]
61    #[case(2, "foo")]
62    #[case(3, "foo")]
63    #[case(4, "Xfoo")]
64    #[case(5, "XXfoo")]
65    fn test_pad_char(#[case] n: usize, #[case] want: &str) {
66        assert_eq!(Ok(want.to_string()), pad_char("foo", n, 'X'));
67    }
68
69    #[test]
70    fn test_pad_char_0() {
71        assert_eq!(Err("invalid size"), pad_char("foo", 0, 'X'))
72    }
73
74    #[test]
75    fn test_nopad_char() {
76        assert_ne!(Ok("foobar".to_string()), pad_char("foo", 6, 'X'))
77    }
78
79    #[rstest]
80    #[case(2, "foo")]
81    #[case(3, "foo")]
82    #[case(4, "Xfoo")]
83    #[case(5, "XXfoo")]
84    fn test_pad_with(#[case] n: usize, #[case] want: &str) {
85        assert_eq!(Ok(want.to_string()), pad_with("foo", n, 'X'));
86    }
87
88    #[test]
89    fn test_pad_with_0() {
90        assert_eq!(Err("invalid size"), pad_with("foo", 0, 'X'))
91    }
92
93    #[test]
94    fn test_nopad_with() {
95        assert_ne!(Ok("foobar".to_string()), pad_with("foo", 6, 'X'))
96    }
97}