From e731144025b726670cd85d43acdd93b7636de338 Mon Sep 17 00:00:00 2001 From: Max Audron Date: Tue, 19 Oct 2021 14:03:17 +0200 Subject: add formatting trait for irc codes add an impl off the formatting trait on String to format Strings with the typical irc formatting codes for bold, italic etc --- src/util/formatting/mod.rs | 88 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/util/formatting/mod.rs (limited to 'src/util/formatting/mod.rs') diff --git a/src/util/formatting/mod.rs b/src/util/formatting/mod.rs new file mode 100644 index 0000000..5cfdfa8 --- /dev/null +++ b/src/util/formatting/mod.rs @@ -0,0 +1,88 @@ +mod truncate; +mod color; + +pub use truncate::*; +pub use color::*; + +pub trait Formatting<'r> { + const BOLD: &'r str = "\x02"; + const ITALIC: &'r str = "\x1D"; + const UNDERLINE: &'r str = "\x1F"; + const STRIKETHROUGH: &'r str = "\x1E"; + const MONOSPACE: &'r str = "\x11"; + const COLOR: &'r str = "\x03"; + + fn bold(self) -> Self; + fn italic(self) -> Self; + fn underline(self) -> Self; + fn strikethrough(self) -> Self; + fn monospace(self) -> Self; + // fn color(self, color: Color) -> Self; +} + +impl<'r> Formatting<'r> for String { + fn bold(mut self) -> Self { + self.insert_str(0, Self::BOLD); + self.push_str(Self::BOLD); + + return self; + } + + fn italic(mut self) -> Self { + self.insert_str(0, Self::ITALIC); + self.push_str(Self::ITALIC); + + return self; + } + + fn underline(mut self) -> Self { + self.insert_str(0, Self::UNDERLINE); + self.push_str(Self::UNDERLINE); + + return self; + } + + fn strikethrough(mut self) -> Self { + self.insert_str(0, Self::STRIKETHROUGH); + self.push_str(Self::STRIKETHROUGH); + + return self; + } + + fn monospace(mut self) -> Self { + self.insert_str(0, Self::MONOSPACE); + self.push_str(Self::MONOSPACE); + + return self; + } + + // TODO implement color codes + // fn color(mut self, foreground: Option, background: Option) -> Self { + // self.insert_str(0, Self::COLOR); + // self.push_str(Self::COLOR); + + // return self; + // } +} + +#[cfg(all(test, feature = "bench"))] +mod bench { + use super::*; + use test::Bencher; + + #[bench] + fn bench_mut(b: &mut Bencher) { + b.iter(|| { + let mut src = "test".to_string(); + src.bold() + }); + } + + #[bench] + fn bench_format(b: &mut Bencher) { + b.iter(|| { + let mut src = "test".to_string(); + src.italic() + }); + } +} -- cgit v1.2.3