indentasy/
lib.rs

1#![doc = include_str!("../README.md")]
2
3/// Indent text
4///
5/// # Examples
6///
7/// ```rust
8/// fn hello_newline_world() {
9///     assert_eq!("    hello\n    world", indentasy::indent("hello\nworld", 1, 4));
10/// }
11///
12/// fn newline_hello_newline_world() {
13///     assert_eq!(
14///         "\n    hello\n    world",
15///         indentasy::indent("\nhello\nworld", 1, 4)
16///     );
17/// }
18///
19/// fn hello_newline_world_indent_with_tab() {
20///     assert_eq!("\thello\n\tworld", indentasy::indent("hello\nworld", 1, 0));
21/// }
22///
23/// fn hello_newline_world_with_String() {
24///     assert_eq!(
25///         "    hello\n    world",
26///         indentasy::indent("hello\nworld".to_string(), 1, 4)
27///     );
28/// }
29/// ```
30pub fn indent<S: AsRef<str>>(s: S, num_of_indents: usize, spaces_per_indent: usize) -> String {
31    s.as_ref()
32        .lines()
33        .enumerate()
34        .map(|(i, line)| {
35            let tmp;
36            [
37                if i > 0 { "\n" } else { "" },
38                if !line.is_empty() {
39                    tmp = if spaces_per_indent < 1 {
40                        vec![""; num_of_indents + 1].join("\t")
41                    } else {
42                        vec![""; num_of_indents + 1]
43                            .join(&vec![""; spaces_per_indent + 1].join(" "))
44                    };
45                    &tmp
46                } else {
47                    ""
48                },
49                line,
50            ]
51            .concat()
52        })
53        .collect::<String>()
54}
55
56#[cfg(test)]
57mod tests {
58    #[test]
59    fn hello_newline_world() {
60        assert_eq!("    hello\n    world", super::indent("hello\nworld", 1, 4));
61    }
62
63    #[test]
64    fn newline_hello_newline_world() {
65        assert_eq!(
66            "\n    hello\n    world",
67            super::indent("\nhello\nworld", 1, 4)
68        );
69    }
70
71    #[test]
72    fn hello_newline_world_indent_with_tab() {
73        assert_eq!("\thello\n\tworld", super::indent("hello\nworld", 1, 0));
74    }
75
76    #[test]
77    fn hello_newline_world_with_String() {
78        assert_eq!(
79            "    hello\n    world",
80            super::indent("hello\nworld".to_string(), 1, 4)
81        );
82    }
83}