summaryrefslogtreecommitdiff
path: root/src/center.rs
diff options
context:
space:
mode:
authorElias Fleckenstein <eliasfleckenstein@web.de>2022-07-31 23:38:56 +0200
committerElias Fleckenstein <eliasfleckenstein@web.de>2022-07-31 23:38:56 +0200
commit666f40fd54dbe94bd26917edf8956e83c6626ece (patch)
tree4afdb172f230f5d7148224dbc4096f086315cd7d /src/center.rs
downloadkotowaza-666f40fd54dbe94bd26917edf8956e83c6626ece.tar.xz
Initial commit
Diffstat (limited to 'src/center.rs')
-rw-r--r--src/center.rs37
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
+ }
+}