From 666f40fd54dbe94bd26917edf8956e83c6626ece Mon Sep 17 00:00:00 2001 From: Elias Fleckenstein Date: Sun, 31 Jul 2022 23:38:56 +0200 Subject: Initial commit --- src/center.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/center.rs (limited to 'src/center.rs') 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 + } +} -- cgit v1.2.3