matrix_display/
pad.rs

1pub use self::pad::horizontal_pad;
2pub use self::pad::Pad;
3
4extern crate unicode_width;
5
6#[cfg(test)]
7mod pad_tests {
8    use super::{horizontal_pad, Pad};
9    #[test]
10    pub fn adds_up_to_correct_size() {
11        let pad = Pad::new(12, 3);
12        assert_eq!(12, pad.before + 3 + pad.after);
13    }
14    #[test]
15    pub fn centered() {
16        let pad = Pad::new(10, 2);
17        assert_eq!(4, pad.before);
18        assert_eq!(4, pad.after);
19    }
20    #[test]
21    pub fn odd_total() {
22        let pad = Pad::new(11, 3);
23        assert_eq!(4, pad.before);
24        assert_eq!(4, pad.after);
25    }
26    #[test]
27    pub fn no_pad_even() {
28        let pad = Pad::new(4, 4);
29        assert_eq!(0, pad.before);
30        assert_eq!(0, pad.after);
31    }
32    #[test]
33    pub fn no_pad_odd() {
34        let pad = Pad::new(1, 1);
35        assert_eq!(0, pad.before);
36        assert_eq!(0, pad.after);
37    }
38    #[test]
39    pub fn pad_ascii() {
40        let output = horizontal_pad(8, "ascii", ' ');
41        assert_eq!(output, "  ascii ");
42    }
43    #[test]
44    pub fn pad_cjk() {
45        let output = horizontal_pad(8, "中文", ' ');
46        assert_eq!(output, "  中文  ");
47    }
48}
49
50mod pad {
51
52    use crate::pad::unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
53    use std;
54
55    pub struct Pad {
56        pub before: usize,
57        pub after: usize,
58    }
59    impl Pad {
60        pub fn new(total: usize, content: usize) -> Pad {
61            Pad {
62                before: (total - content) / 2 + (total - content) % 2,
63                after: (total - content) / 2,
64            }
65        }
66    }
67
68    /// ## Panic When:
69    /// - pad char width > 1.
70    pub fn horizontal_pad(width: usize, s: &str, c: char) -> String {
71        assert!(c.width().unwrap_or(0) <= 1, "{:?} width > 1", c);
72
73        let pad = Pad::new(width, s.width());
74        std::iter::repeat(c).take(pad.before).collect::<String>()
75            + s
76            + &std::iter::repeat(c).take(pad.after).collect::<String>()
77    }
78}