Skip to content

Commit

Permalink
another prettystring implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
egithinji committed Apr 21, 2022
1 parent 644596e commit 0055b63
Showing 1 changed file with 16 additions and 27 deletions.
43 changes: 16 additions & 27 deletions src/styled/string.rs
Expand Up @@ -9,64 +9,53 @@

use crate::Ansi;

const SUFFIX_LENGTH:usize = 7;

pub struct PrettyString {
formatted_text: String,
length_original: usize,
pub struct PrettyString<'a> {
ansi: Ansi,
original: &'a str,
}

impl PrettyString {
impl<'a> PrettyString<'a> {
/// Create a new [`PrettyString`] from the given text and style.
pub fn new(text: &str, format: Ansi) -> Self {
pub fn new(text: &'a str, format: Ansi) -> Self {
PrettyString {
formatted_text: format.paint_text(text),
length_original: text.len(),
ansi: format,
original: text,
}
}

/// Get the raw (unstyled) text contained in this [`PrettyString`].
pub fn raw(&self) -> &str {
let (_, o) = self.get_style_and_original();
o
self.original
}

/// Get the current style of this [`PrettyString`].
pub fn style(&self) -> Option<Ansi> {
Ansi::parse_ansi_text(&self.formatted_text)
Some(self.ansi)
}

/// Get the formatted text contained in this [`PrettyString`].
pub fn value(&self) -> &str {
&self.formatted_text
pub fn value(&self) -> String {
self.ansi.paint_text(self.original)
}

/// Update the style of this [`PrettyString`] using the given function `F`.
///
/// `F` will receive the current style and should return the new or modified style.
pub fn modify_style<F: FnOnce(Option<Ansi>) -> Option<Ansi>>(&mut self, f: F) {
if let Some(f) = f(self.style()) {
let (original_t, _) = self.get_style_and_original();
let p = PrettyString::new(original_t, f);
self.formatted_text = p.formatted_text;

if let Some(a) = f(self.style()) {
self.ansi = a;
}
}

fn get_style_and_original(&self) -> (&str, &str) {
let formatting_length = self.formatted_text.len() - SUFFIX_LENGTH - self.length_original;
let style = &self.formatted_text[0..formatting_length];
let original = &self.formatted_text[formatting_length..self.formatted_text.len() - SUFFIX_LENGTH];
(style, original)
}
}

impl std::fmt::Display for PrettyString {
impl std::fmt::Display for PrettyString<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.value())
}
}

impl From<PrettyString> for String {
impl From<PrettyString<'_>> for String {
fn from(pretty: PrettyString) -> Self {
pretty.to_string()
}
Expand Down

0 comments on commit 0055b63

Please sign in to comment.