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
335
336
337
338
339
340
341
//! This module defines several useful string variants, including copy-on-write and immutable
//! implementations.

use std::borrow::Cow;

use crate::impls;
use crate::clone::*;
use std::ops::Deref;
use std::rc::Rc;
use derive_more::*;



// =================
// === StringOps ===
// =================

pub trait StringOps {
    fn is_enclosed(&self, first_char:char, last_char:char) -> bool;
}

impl<T:AsRef<str>> StringOps for T {
    /// Check if given string starts and ends with given characters.
    ///
    /// Optimized to be O(1) if both characters are within ASCII range.
    fn is_enclosed(&self, first_char:char, last_char:char) -> bool {
        let text = self.as_ref();
        if first_char.is_ascii() && last_char.is_ascii() {
            let bytes = text.as_bytes();
            bytes.first() == Some(&(first_char as u8)) && bytes.last() == Some(&(last_char as u8))
        } else {
            let mut chars = text.chars();
            let first     = chars.next();
            let last      = chars.last().or(first);
            first == Some(first_char) && last == Some(last_char)
        }
    }
}



// ===========
// === Str ===
// ===========

/// Abstraction for any kind of string as an argument. Functions defined as
/// `fn test<S:Str>(s: Str) { ... }` can be called with `String`, `&String`, and `&str` without
/// requiring caller to know the implementation details. Moreover, the definition can decide if it
/// needs allocation or not. Calling `s.as_ref()` will never allocate, while `s.into()` will
/// allocate only when necessary.
pub trait Str = Into<String> + AsRef<str>;



// =================
// === CowString ===
// =================

// === Definition ===

/// A copy-on-write String implementation. It is a newtype wrapper for `Cow<'static,str>` and
/// provides many useful impls for efficient workflow. Use it whenever you want to store a string
/// but you are not sure if the string will be allocated or not. This way you can store a static
/// slice as long as you can and switch to allocated String on demand.
#[derive(Clone,Debug,Default,Display)]
pub struct CowString(Cow<'static,str>);


// === Conversions From CowString ===

impls!{ From <&CowString> for String { |t| t.clone().into() } }
impls!{ From <CowString>  for String { |t| t.0.into()       } }


// === Conversions To CowString ===

impls!{ From <Cow<'static,str>>  for CowString { |t| Self(t)              } }
impls!{ From <&Cow<'static,str>> for CowString { |t| Self(t.clone())      } }
impls!{ From <&'static str>      for CowString { |t| Self(t.into())       } }
impls!{ From <String>            for CowString { |t| Self(t.into())       } }
impls!{ From <&String>           for CowString { |t| t.to_string().into() } }
impls!{ From <&CowString>        for CowString { |t| t.clone()            } }


// === Instances ===

impl Deref for CowString {
    type Target = str;
    fn deref(&self) -> &str {
        self.0.deref()
    }
}

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



// ================
// === ImString ===
// ================

/// Immutable string implementation with a fast clone implementation.
#[derive(Clone,CloneRef,Debug,Default,Eq,Hash,PartialEq)]
pub struct ImString {
    content : Rc<String>
}

impl ImString {
    /// Constructor.
    pub fn new(content:impl Into<String>) -> Self {
        let content = Rc::new(content.into());
        Self {content}
    }

    /// Extract a string slice containing the entire string.
    pub fn as_str(&self) -> &str {
        &self.content
    }
}

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

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

impl AsRef<ImString> for ImString {
    fn as_ref(&self) -> &ImString {
        self
    }
}

impl AsRef<String> for ImString {
    fn as_ref(&self) -> &String {
        self.content.as_ref()
    }
}

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

impl From<String> for ImString {
    fn from(t:String) -> Self {
        Self::new(t)
    }
}

impl From<&String> for ImString {
    fn from(t:&String) -> Self {
        Self::new(t)
    }
}

impl From<&&String> for ImString {
    fn from(t:&&String) -> Self {
        Self::new(*t)
    }
}

impl From<&str> for ImString {
    fn from(t:&str) -> Self {
        Self::new(t)
    }
}

impl From<&&str> for ImString {
    fn from(t:&&str) -> Self {
        Self::new(*t)
    }
}

impl From<ImString> for String {
    fn from(value:ImString) -> Self {
        match Rc::try_unwrap(value.content) {
            Ok(str) => str,
            Err(rc) => rc.deref().clone(),
        }
    }
}

impl PartialEq<&str> for ImString {
    fn eq(&self, other:&&str) -> bool {
        self.content.as_ref().eq(other)
    }
}

impl PartialEq<String> for ImString {
    fn eq(&self, other:&String) -> bool {
        self.content.as_ref().eq(other)
    }
}

impl PartialEq<ImString> for String {
    fn eq(&self, other:&ImString) -> bool {
        self.eq(other.content.as_ref())
    }
}


// === Macros ===

/// Defines a newtype for `ImString`.
#[macro_export]
macro_rules! im_string_newtype {
    ($($(#$meta:tt)* $name:ident),* $(,)?) => {$(
        $(#$meta)*
        #[derive(Clone,CloneRef,Debug,Default,Eq,Hash,PartialEq)]
        pub struct $name {
            content : ImString
        }

        impl $name {
            /// Constructor.
            pub fn new(content:impl Into<ImString>) -> Self {
                let content = content.into();
                Self {content}
            }
        }

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

        impl AsRef<$name> for $name {
            fn as_ref(&self) -> &$name {
                self
            }
        }

        impl AsRef<ImString> for $name {
            fn as_ref(&self) -> &ImString {
                self.content.as_ref()
            }
        }

        impl AsRef<String> for $name {
            fn as_ref(&self) -> &String {
                self.content.as_ref()
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                self.content.as_ref()
            }
        }

        impl From<String> for $name {
            fn from(t:String) -> Self {
                Self::new(t)
            }
        }

        impl From<&String> for $name {
            fn from(t:&String) -> Self {
                Self::new(t)
            }
        }

        impl From<&&String> for $name {
            fn from(t:&&String) -> Self {
                Self::new(t)
            }
        }

        impl From<&str> for $name {
            fn from(t:&str) -> Self {
                Self::new(t)
            }
        }

        impl From<&&str> for $name {
            fn from(t:&&str) -> Self {
                Self::new(t)
            }
        }
    )*};
}



// =============
// === Tests ===
// =============

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

    #[test]
    fn test_string_ops() {
        // === Matching against ascii ===
        assert!("{}".is_enclosed('{','}'));
        assert!("{ }".is_enclosed('{','}'));
        assert!(!"{".is_enclosed('{','}'));
        assert!(!"{a".is_enclosed('{','}'));
        assert!(!"a}".is_enclosed('{','}'));
        assert!(!"}".is_enclosed('{','}'));
        assert!(!"".is_enclosed('{','}'));
        assert!("{a}".is_enclosed('{','}'));
        assert!("{字}".is_enclosed('{','}'));
        assert!(!"{".is_enclosed('{','}'));
        assert!(!"{字".is_enclosed('{','}'));
        assert!(!"字}".is_enclosed('{','}'));
        assert!(!"}".is_enclosed('{','}'));
        assert!(!"".is_enclosed('{','}'));


        // === Matching against non-ascii ===
        assert!("【】".is_enclosed('【','】'));
        assert!("【 】".is_enclosed('【','】'));
        assert!("【 a】".is_enclosed('【','】'));
        assert!(!"【".is_enclosed('【','】'));
        assert!(!"【a".is_enclosed('【','】'));
        assert!(!"a】".is_enclosed('【','】'));
        assert!(!"】".is_enclosed('【','】'));
        assert!(!"".is_enclosed('【','】'));


        // === Edge case of matching single char string ===
        assert!("{".is_enclosed('{','{'));
        assert!("【".is_enclosed('【','【'));
    }
}