]> git.lizzy.rs Git - kotowaza.git/blob - src/center.rs
Add LICENSE
[kotowaza.git] / src / center.rs
1 use unicode_width::UnicodeWidthChar;
2
3 pub trait Center {
4         fn center(&self, term_width: usize) -> Self;
5 }
6
7 impl Center for String {
8         fn center(&self, term_width: usize) -> Self {
9                 let mut result = String::new();
10                 let mut buffer = String::new();
11                 let mut buffer_width = 0;
12
13                 let max = self.chars().count() - 1;
14
15                 for (i, c) in self.chars().enumerate() {
16                         buffer_width += UnicodeWidthChar::width(c)
17                                 .unwrap();
18
19                         buffer.push(c);
20
21                         if i == max || buffer_width >= term_width - 12 {
22                                 result.push_str(&String::from(" ")
23                                         .repeat((term_width - buffer_width) / 2));
24                                 result.push_str(&buffer);
25
26                                 if i != max {
27                                         result.push('\n');
28                                 }
29
30                                 buffer.clear();
31                                 buffer_width = 0;
32                         }
33                 }
34
35                 result
36         }
37 }