redgold_schema/util/
lang_util.rs

1use crate::helpers::easy_json::json_or;
2use crate::structs::ErrorInfo;
3use itertools::Itertools;
4use serde::Serialize;
5use crate::{ErrorInfoContext, RgResult};
6
7pub trait SameResult<T> {
8    fn combine(self) -> T;
9}
10
11impl<T> SameResult<T> for Result<T, T> {
12    fn combine(self) -> T {
13        self.unwrap_or_else(|e| e)
14    }
15}
16
17pub fn remove_whitespace(s: &str) -> String {
18    s.chars().filter(|c| !c.is_whitespace()).collect()
19}
20
21pub trait PersistentRun {
22    fn run(&mut self) -> Result<(), ErrorInfo>;
23}
24
25
26pub trait JsonCombineResult {
27    fn json_or_combine(self) -> String;
28}
29
30impl<T, E> JsonCombineResult for Result<T, E>
31where T: Serialize, E: Serialize {
32    fn json_or_combine(self) -> String {
33        self.map(|x| json_or(&x))
34            .map_err(|x| json_or(&x))
35            .combine()
36    }
37}
38
39pub trait VecAddBy<T, K> {
40    fn add_by(&mut self, other: T, func: fn(&T) -> &K) -> Vec<T>;
41}
42
43impl<T, K> VecAddBy<T, K> for Vec<T> where K : PartialEq, T: Clone {
44    fn add_by(&mut self, other: T, func: fn(&T) -> &K) -> Vec<T> {
45        let k = func(&other);
46        let mut res = self.iter().filter(|x| func(x) != k)
47            .map(|x| x.clone()
48            ).collect_vec();
49        res.push(other);
50        res
51    }
52}
53
54pub trait AnyPrinter{
55    fn print(&self);
56}
57
58impl<T> AnyPrinter for T where T: std::fmt::Display {
59    fn print(&self) {
60        println!("{}", self);
61    }
62}
63
64pub trait WithMaxLengthString {
65    fn with_max_length(&self, max: usize) -> String;
66    fn last_n(&self, n: usize) -> String;
67}
68
69impl WithMaxLengthString for String {
70    fn with_max_length(&self, max: usize) -> String {
71        if self.len() > max {
72            format!("{}", &self[..max])
73        } else {
74            self.clone()
75        }
76    }
77
78    fn last_n(&self, n: usize) -> String {
79        if self.len() > n {
80            format!("{}", &self[self.len() - n..])
81        } else {
82            self.clone()
83        }
84    }
85}
86
87pub fn make_ascii_titlecase(s: &mut str) -> String {
88    if let Some(r) = s.get_mut(0..1) {
89        r.make_ascii_uppercase();
90    }
91    return s.to_string();
92}