python/
string.rs

1use std::fmt; // use std::ops::Index;
2use std::str::Chars;
3
4use crate::_Object;
5
6#[derive(Clone)]
7#[derive(Hash)]
8#[derive(Eq)]
9#[derive(PartialEq)]
10/// the struct that handles String and &str
11pub struct _String {
12    /// the core field
13    _string: String,
14}
15
16impl _String {
17    /// constructor: creates a new _String struct
18    pub fn new() -> _String {
19        _String {
20            _string: String::new(),
21        }
22    }
23
24    #[inline]
25    /// _String.index(0) -> first char
26    pub fn index(&self, _index: usize) -> Option<char> {
27        self._string.chars().nth(_index)
28    }
29
30    /// _String.get(0) -> first char
31    pub fn get(&self, _index: usize) -> Option<char> {
32        self.index(_index)
33    }
34}
35
36impl From<Chars<'_>> for _String {
37    fn from(_chars: Chars) -> Self {
38        let mut allocator = String::new();
39        for _char in _chars {
40            allocator.push(_char)
41        }
42        _String {
43            _string: allocator
44        }
45    }
46}
47
48impl From<&str> for _String {
49    fn from(_str: &str) -> Self {
50        _String {
51            _string: String::from(_str),
52        }
53    }
54}
55impl From<String> for _String {
56    fn from(_string: String) -> Self {
57        _String {
58            _string,
59        }
60    }
61}
62
63impl Default for _String {
64    fn default() -> Self {
65        Self::new()
66    }
67}
68
69impl _Object for _String {
70    fn __repr__(&self) -> String {
71        format!("'{}'", self._string)
72    }
73
74    fn __str__(&self) -> String {
75        self._string.clone()
76    }
77}
78
79impl fmt::Display for _String {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "{}", self._string)
82    }
83}
84
85impl fmt::Debug for _String {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{:?}", self._string)
88    }
89}
90
91impl PartialEq<String> for _String {
92    fn eq(&self, other: &String) -> bool {
93        self._string == *other
94    }
95}
96
97
98// impl Index<usize> for _String {
99//     type Output = char;
100//     fn index(&self, _index: usize) -> &Self::Output {
101//         self._string.index(_index)
102//     }
103// }