1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use std::borrow::{Borrow, Cow};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Add, Deref};

#[cfg(feature = "pylib")]
use pyo3::{FromPyObject, IntoPy, PyAny, PyObject, Python};

pub type ArcStr = std::sync::Arc<str>;

/// Used to hold an immutable string.
///
/// It can construct as a const (by Str::ever).
#[derive(Debug, Clone, Eq)]
pub enum Str {
    Rc(ArcStr),
    Static(&'static str),
}

#[cfg(feature = "pylib")]
impl FromPyObject<'_> for Str {
    fn extract(ob: &PyAny) -> pyo3::PyResult<Self> {
        let s = ob.extract::<String>()?;
        Ok(Str::Rc(s.into()))
    }
}

#[cfg(feature = "pylib")]
impl IntoPy<PyObject> for Str {
    fn into_py(self, py: Python<'_>) -> PyObject {
        (&self[..]).into_py(py)
    }
}

impl PartialEq for Str {
    #[inline]
    fn eq(&self, other: &Str) -> bool {
        self[..] == other[..]
    }
}

impl PartialEq<Str> for &mut Str {
    #[inline]
    fn eq(&self, other: &Str) -> bool {
        self[..] == other[..]
    }
}

impl PartialEq<str> for Str {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self[..] == other[..]
    }
}

impl PartialEq<&str> for Str {
    #[inline]
    fn eq(&self, other: &&str) -> bool {
        self[..] == other[..]
    }
}

impl PartialEq<String> for Str {
    #[inline]
    fn eq(&self, other: &String) -> bool {
        self[..] == other[..]
    }
}

impl Add<&str> for Str {
    type Output = Str;
    #[inline]
    fn add(self, other: &str) -> Str {
        Str::from(&format!("{self}{other}"))
    }
}

impl Hash for Str {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Str::Rc(s) => s[..].hash(state),
            Str::Static(s) => (*s).hash(state),
        }
    }
}

impl fmt::Display for Str {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Str::Rc(s) => write!(f, "{s}"),
            Str::Static(s) => write!(f, "{s}"),
        }
    }
}

impl From<&Str> for String {
    #[inline]
    fn from(s: &Str) -> Self {
        s.to_string()
    }
}

impl From<Str> for String {
    #[inline]
    fn from(s: Str) -> Self {
        s.to_string()
    }
}

impl<'a> From<Str> for Cow<'a, str> {
    fn from(s: Str) -> Self {
        match s {
            Str::Static(s) => Cow::Borrowed(s),
            Str::Rc(s) => Cow::Owned(s.to_string()),
        }
    }
}

// &'static str -> &strになってしまわないように
// あえて`impl<S: Into<Str>> From<S> for Str { ... }`はしない
impl From<&'static str> for Str {
    #[inline]
    fn from(s: &'static str) -> Self {
        Str::ever(s)
    }
}

impl From<&String> for Str {
    #[inline]
    fn from(s: &String) -> Self {
        Str::Rc((s[..]).into())
    }
}

impl From<String> for Str {
    #[inline]
    fn from(s: String) -> Self {
        Str::Rc((s[..]).into())
    }
}

impl From<&ArcStr> for Str {
    #[inline]
    fn from(s: &ArcStr) -> Self {
        Str::Rc(s.clone())
    }
}

impl From<ArcStr> for Str {
    #[inline]
    fn from(s: ArcStr) -> Self {
        Str::Rc(s)
    }
}

impl From<&Str> for Str {
    #[inline]
    fn from(s: &Str) -> Self {
        match s {
            Str::Rc(s) => Str::Rc(s.clone()),
            Str::Static(s) => Str::Static(s),
        }
    }
}

impl From<Cow<'_, str>> for Str {
    #[inline]
    fn from(s: Cow<'_, str>) -> Self {
        match s {
            Cow::Borrowed(s) => Str::rc(s),
            Cow::Owned(s) => Str::Rc(s.into()),
        }
    }
}

impl Deref for Str {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.borrow()
    }
}

impl Borrow<str> for Str {
    #[inline]
    fn borrow(&self) -> &str {
        match self {
            Str::Rc(s) => &s[..],
            Str::Static(s) => s,
        }
    }
}

impl AsRef<str> for Str {
    fn as_ref(&self) -> &str {
        self.borrow()
    }
}

impl Str {
    pub const fn ever(s: &'static str) -> Self {
        Str::Static(s)
    }

    pub fn rc(s: &str) -> Self {
        Str::Rc(s.into())
    }

    pub fn leak(self) -> &'static str {
        match self {
            Str::Rc(s) => Box::leak(s.into()),
            Str::Static(s) => s,
        }
    }

    pub fn into_rc(self) -> ArcStr {
        match self {
            Str::Rc(s) => s,
            Str::Static(s) => ArcStr::from(s),
        }
    }

    pub fn is_uppercase(&self) -> bool {
        self.chars()
            .next()
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
    }

    /// split string with multiple separators
    /// ```rust
    /// # use erg_common::str::Str;
    /// let s = Str::rc("a.b::c");
    /// assert_eq!(s.split_with(&[".", "::"]), vec!["a", "b", "c"]);
    /// let s = Str::rc("ああ.いい::うう");
    /// assert_eq!(s.split_with(&[".", "::"]), vec!["ああ", "いい", "うう"]);
    /// let s = Str::rc("abc");
    /// assert_eq!(s.split_with(&[".", "::"]), vec!["abc"]);
    /// ```
    pub fn split_with(&self, seps: &[&str]) -> Vec<&str> {
        let mut result = vec![];
        let mut last_offset = 0;
        for (offset, _c) in self.char_indices() {
            for sep in seps {
                if self[offset..].starts_with(sep) {
                    result.push(&self[last_offset..offset]);
                    last_offset = offset + sep.len();
                }
            }
        }
        result.push(&self[last_offset..]);
        result
    }

    pub fn reversed(&self) -> Str {
        Str::rc(&self.chars().rev().collect::<String>())
    }

    /// Note that replacements may be chained because it attempt to rewrite in sequence
    pub fn multi_replace(&self, paths: &[(&str, &str)]) -> Self {
        let mut self_ = self.to_string();
        for (from, to) in paths {
            self_ = self_.replace(from, to);
        }
        Str::rc(&self_)
    }

    pub fn is_snake_case(&self) -> bool {
        self.chars().all(|c| !c.is_uppercase())
    }

    pub fn to_snake_case(&self) -> Str {
        let mut ret = String::new();
        let mut prev = '_';
        for c in self.chars() {
            if c.is_ascii_uppercase() {
                if prev != '_' {
                    ret.push('_');
                }
                ret.push(c.to_ascii_lowercase());
            } else {
                ret.push(c);
            }
            prev = c;
        }
        Str::rc(&ret)
    }

    pub fn find_sub<'a>(&self, pats: &[&'a str]) -> Option<&'a str> {
        pats.iter().find(|&&pat| self.contains(pat)).copied()
    }

    /// ```
    /// # use erg_common::str::Str;
    /// let s = Str::rc("\n");
    /// assert_eq!(&s.escape()[..], "\\n");
    /// let s = Str::rc("\\");
    /// assert_eq!(&s.escape()[..], "\\\\");
    /// ```
    pub fn escape(&self) -> Str {
        self.multi_replace(&[
            ("\\", "\\\\"),
            ("\0", "\\0"),
            ("\r", "\\r"),
            ("\n", "\\n"),
            ("\"", "\\\""),
            ("\'", "\\'"),
        ])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_split_with() {
        assert_eq!(
            Str::ever("aa::bb.cc").split_with(&[".", "::"]),
            vec!["aa", "bb", "cc"]
        );
        assert_eq!(
            Str::ever("aa::bb.cc").split_with(&["::", "."]),
            vec!["aa", "bb", "cc"]
        );
        assert_eq!(
            Str::ever("aaxxbbyycc").split_with(&["xx", "yy"]),
            vec!["aa", "bb", "cc"]
        );
        assert_ne!(
            Str::ever("aaxxbbyycc").split_with(&["xx", "yy"]),
            vec!["aa", "bb", "ff"]
        );
    }
}