diff options
Diffstat (limited to 'src/center.rs')
-rw-r--r-- | src/center.rs | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/center.rs b/src/center.rs new file mode 100644 index 0000000..173ef63 --- /dev/null +++ b/src/center.rs @@ -0,0 +1,37 @@ +use unicode_width::UnicodeWidthChar; + +pub trait Center { + fn center(&self, term_width: usize) -> Self; +} + +impl Center for String { + fn center(&self, term_width: usize) -> Self { + let mut result = String::new(); + let mut buffer = String::new(); + let mut buffer_width = 0; + + let max = self.chars().count() - 1; + + for (i, c) in self.chars().enumerate() { + buffer_width += UnicodeWidthChar::width(c) + .unwrap(); + + buffer.push(c); + + if i == max || buffer_width >= term_width - 12 { + result.push_str(&String::from(" ") + .repeat((term_width - buffer_width) / 2)); + result.push_str(&buffer); + + if i != max { + result.push('\n'); + } + + buffer.clear(); + buffer_width = 0; + } + } + + result + } +} |