datex_core/values/core_values/
text.rs

1use std::{
2    fmt::Display,
3    ops::{Add, AddAssign},
4};
5
6use crate::values::traits::structural_eq::StructuralEq;
7
8use super::super::core_value_trait::CoreValueTrait;
9
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct Text(pub String);
12
13impl Display for Text {
14    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
15        write!(f, "\"{}\"", self.0)
16    }
17}
18
19impl Text {
20    pub fn length(&self) -> usize {
21        self.0.len()
22    }
23    pub fn to_uppercase(&self) -> Text {
24        Text(self.0.to_uppercase())
25    }
26    pub fn to_lowercase(&self) -> Text {
27        Text(self.0.to_lowercase())
28    }
29    pub fn as_str(&self) -> &str {
30        &self.0
31    }
32    pub fn as_string(&self) -> String {
33        self.0.clone()
34    }
35}
36
37impl Text {
38    pub fn reverse(&mut self) {
39        let reversed = self.0.chars().rev().collect::<String>();
40        self.0 = reversed;
41    }
42}
43
44impl CoreValueTrait for Text {}
45
46impl StructuralEq for Text {
47    fn structural_eq(&self, other: &Self) -> bool {
48        self.0 == other.0
49    }
50}
51
52/// The froms are used for this magic. This will automatically convert
53/// the Rust types to Text when using the += operator.
54impl From<&str> for Text {
55    fn from(s: &str) -> Self {
56        Text(s.to_string())
57    }
58}
59
60impl From<String> for Text {
61    fn from(s: String) -> Self {
62        Text(s)
63    }
64}
65
66/// Allow TypedDatexValue<Text> += String and TypedDatexValue<Text> += &str
67/// This can never panic since the Text::from from string will always succeed
68impl AddAssign<Text> for Text {
69    fn add_assign(&mut self, rhs: Text) {
70        self.0 += &rhs.0;
71    }
72}
73
74impl Add for Text {
75    type Output = Self;
76
77    fn add(self, rhs: Self) -> Self::Output {
78        Text(self.0 + &rhs.0)
79    }
80}
81
82impl Add for &Text {
83    type Output = Text;
84
85    fn add(self, rhs: Self) -> Self::Output {
86        Text(self.0.clone() + &rhs.0)
87    }
88}
89
90impl Add<Text> for &Text {
91    type Output = Text;
92
93    fn add(self, rhs: Text) -> Self::Output {
94        Text(self.0.clone() + &rhs.0)
95    }
96}
97
98impl Add<&Text> for Text {
99    type Output = Text;
100
101    fn add(self, rhs: &Text) -> Self::Output {
102        Text(self.0 + &rhs.0)
103    }
104}
105
106impl Add<&str> for Text {
107    type Output = Text;
108
109    fn add(self, rhs: &str) -> Self::Output {
110        Text(self.0 + rhs)
111    }
112}