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
//! String object
use super::{BoxedObject, List, Object, RefValue};
use crate::value;
use num::{ToPrimitive, Zero};
use num_bigint::{BigInt, Sign};
use num_parse::*;
use tokay_macros::tokay_method;
extern crate self as tokay;

#[derive(Clone, PartialEq, PartialOrd)]
pub struct Str {
    string: String,
}

impl Object for Str {
    fn severity(&self) -> u8 {
        10
    }

    fn name(&self) -> &'static str {
        "str"
    }

    fn repr(&self) -> String {
        let mut ret = String::with_capacity(self.string.len() + 2);
        ret.push('"');

        for ch in self.string.chars() {
            match ch {
                '\\' => ret.push_str("\\\\"),
                '\"' => ret.push_str("\\\""),
                '\n' => ret.push_str("\\n"),
                '\r' => ret.push_str("\\r"),
                '\t' => ret.push_str("\\t"),
                ch => ret.push(ch),
            }
        }

        ret.push('"');
        ret
    }

    fn is_true(&self) -> bool {
        self.len() > 0
    }

    fn to_i64(&self) -> Result<i64, String> {
        Ok(parse_int::<i64>(&self.string).unwrap_or(0))
    }

    fn to_f64(&self) -> Result<f64, String> {
        // todo: JavaScript-style parseFloat-like behavior?
        match self.string.parse::<f64>() {
            Ok(f) => Ok(f),
            Err(_) => Ok(0.0),
        }
    }

    fn to_usize(&self) -> Result<usize, String> {
        Ok(parse_uint::<usize>(&self.string).unwrap_or(0))
    }

    fn to_string(&self) -> String {
        self.string.clone()
    }

    fn to_bigint(&self) -> Result<BigInt, String> {
        Ok(parse_int::<BigInt>(&self.string).unwrap_or(BigInt::zero()))
    }
}

impl Str {
    /// Returns the &str slice of the Str object.
    pub fn as_str(&self) -> &str {
        &self.string
    }

    tokay_method!("str : @value", Ok(RefValue::from(value.to_string())));

    tokay_method!("str_len : @s", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        Ok(RefValue::from(
            string.object::<Str>().unwrap().chars().count(),
        ))
    });

    tokay_method!("str_byteslen : @s", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        Ok(RefValue::from(string.object::<Str>().unwrap().len()))
    });

    tokay_method!("str_get_item : @s, item, default=void", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let string = string.object::<Str>().unwrap();
        let mut item = item.to_bigint()?;

        // In case the item index is negative, calculate from string's end
        if item.sign() == Sign::Minus {
            item = string.chars().count() + item;

            // If it's still negative, the index is out of bounds
            if item.sign() == Sign::Minus {
                return Ok(default);
            }
        }

        if let Some(ch) = string.chars().nth(item.to_usize().unwrap_or(0)) {
            Ok(RefValue::from(ch))
        } else {
            Ok(default)
        }
    });

    tokay_method!("str_add : @s, append", {
        let mut string = s.to_string();

        if let Some(append) = append.borrow().object::<Str>() {
            string.push_str(append.as_str());
        } else {
            string.push_str(&append.to_string()); // todo: this might me done more memory saving
        }

        Ok(RefValue::from(string))
    });

    tokay_method!("str_endswith : @s, postfix", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let postfix = postfix.borrow();

        let string = string.object::<Str>().unwrap().as_str();

        Ok(if let Some(postfix) = postfix.object::<Str>() {
            value!(string.ends_with(postfix.as_str()))
        } else {
            value!(string.ends_with(&postfix.to_string()))
        })
    });

    tokay_method!("str_mul : @s, count", {
        if let Some(string) = s.borrow().object::<Str>() {
            // string * count
            return Ok(RefValue::from(string.repeat(count.to_usize()?)));
        }

        // count * string is also possible
        Ok(RefValue::from(count.to_string().repeat(s.to_usize()?)))
    });

    tokay_method!("str_join : @s, list", {
        let delimiter = s.to_string();
        let list = List::from(list);

        let mut ret = String::new();

        for item in list.iter() {
            if ret.len() > 0 {
                ret.push_str(&delimiter);
            }

            ret.push_str(&item.to_string());
        }

        Ok(RefValue::from(ret))
    });

    tokay_method!("str_split : @s, sep=void, n=void", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let string = string.object::<Str>().unwrap().as_str();
        let sep = if sep.is_void() {
            " ".to_string()
        } else {
            sep.to_string()
        };

        Ok(RefValue::from(if n.is_void() {
            let mut list = List::new();

            for part in string.split(&sep) {
                list.push(RefValue::from(part))
            }

            list
        } else {
            let n = n.to_usize()?;
            let mut list = List::with_capacity(n + 1);

            for part in string.splitn(n + 1, &sep) {
                list.push(RefValue::from(part))
            }

            list
        }))
    });

    tokay_method!("str_lower : @s", {
        Ok(RefValue::from(s.to_string().to_lowercase()))
    });

    tokay_method!("str_replace : @s, from, to=void, n=void", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let string = string.object::<Str>().unwrap().as_str();
        let from = from.to_string();
        let to = to.to_string();

        Ok(RefValue::from(if n.is_void() {
            string.replace(&from, &to)
        } else {
            string.replacen(&from, &to, n.to_usize()?)
        }))
    });

    tokay_method!("str_startswith : @s, prefix", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let prefix = prefix.borrow();

        let string = string.object::<Str>().unwrap().as_str();

        Ok(if let Some(prefix) = prefix.object::<Str>() {
            value!(string.starts_with(prefix.as_str()))
        } else {
            value!(string.starts_with(&prefix.to_string()))
        })
    });

    tokay_method!("str_substr : @s, start=0, length=void", {
        if !s.is("str") {
            s = RefValue::from(s.to_string());
        }

        let string = s.borrow();
        let string = string.object::<Str>().unwrap().as_str();

        Ok(RefValue::from(if length.is_void() {
            string.chars().skip(start.to_usize()?).collect::<String>()
        } else {
            string
                .chars()
                .skip(start.to_usize()?)
                .take(length.to_usize()?)
                .collect::<String>()
        }))
    });

    tokay_method!("str_upper : @s", {
        Ok(RefValue::from(s.to_string().to_uppercase()))
    });
}

impl std::fmt::Debug for Str {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "\"{}\"", self.string)
    }
}

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

impl std::ops::Deref for Str {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.string
    }
}

impl std::ops::DerefMut for Str {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.string
    }
}

impl From<String> for Str {
    fn from(string: String) -> Self {
        Str { string }
    }
}

impl From<&str> for Str {
    fn from(string: &str) -> Self {
        Str {
            string: string.to_string(),
        }
    }
}

impl From<&str> for RefValue {
    fn from(string: &str) -> Self {
        RefValue::from(string.to_string())
    }
}

impl From<String> for RefValue {
    fn from(string: String) -> Self {
        RefValue::from(Str { string })
    }
}

impl From<Str> for RefValue {
    fn from(string: Str) -> Self {
        RefValue::from(Box::new(string) as BoxedObject)
    }
}

impl From<char> for RefValue {
    fn from(ch: char) -> Self {
        RefValue::from(Str {
            string: format!("{}", ch),
        })
    }
}