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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! String type
//!
//! This type is a wrapper around `String`
//!
//! Like all subtypes, it is hashable, serializable, and fully comparable
//! It is represented as a string in the form of `<value>`
//!
use crate::{operations::*, types::*, Error, Value, ValueTrait, ValueType};
use serde::{Deserialize, Serialize};
use std::ops::{Range, RangeInclusive};

/// Subtype of `Value` that represents a string
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Serialize, Deserialize, Default, Debug)]
pub struct Str(String);
impl_value!(Str, String, |v: &Self| v.inner().clone());

impl From<&str> for Str {
    fn from(value: &str) -> Self {
        <Str>::new(value.into())
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        <Str>::new(value.into()).into()
    }
}

impl Str {
    /// Maps a range of values to a range of bytes in a string coresponding to the same characters
    /// This is necessary because the string is UTF-8 encoded
    /// Can fail if the range is out of bounds, or if the range is not a valid integer range
    fn map_range_to_bytes(&self, range: RangeInclusive<&Value>) -> Result<Range<usize>, Error> {
        let mut range = *Int::try_from((*range.start()).clone())?.inner()
            ..*Int::try_from((*range.end()).clone())?.inner();

        let chars = self.inner().chars().count() as i64;
        if range.start < 0 {
            range.start += chars;
        }
        if range.end < 0 {
            range.end += chars;
        }
        let mut range = range.start as usize..range.end as usize;

        println!("range: {:?}", range);

        // Get the byte-index of the nth character of self.inner()
        // This is necessary because the string is UTF-8 encoded
        // and we need to get the nth character, not the nth byte
        let mut byte_index = 0;
        for _ in 0..range.start {
            byte_index += self
                .inner()
                .get(byte_index..)
                .ok_or(Error::Index {
                    key: range.start.to_string(),
                })?
                .chars()
                .next()
                .ok_or(Error::Index {
                    key: range.start.to_string(),
                })?
                .len_utf8();
        }
        range.start = byte_index;

        // and the start of the next
        let mut byte_index = 0;
        for _ in 0..range.end + 1 {
            byte_index += self
                .inner()
                .get(byte_index..)
                .ok_or(Error::Index {
                    key: range.end.to_string(),
                })?
                .chars()
                .next()
                .ok_or(Error::Index {
                    key: range.end.to_string(),
                })?
                .len_utf8();
        }
        range.end = byte_index - 1;

        Ok(range)
    }

    /// String indexing
    /// Returns a substring
    ///
    /// Although this looks like the IndexingOperationExt trait, it is not
    /// because it returns a string instead of a value
    pub fn substr(&self, index: RangeInclusive<&Value>) -> Result<&str, crate::Error> {
        let range = self.map_range_to_bytes(index)?;
        self.inner()
            .get(range.start..=range.end)
            .ok_or(Error::Index {
                key: format!("{}..{}", range.start, range.end),
            })
    }

    /// Mutable string indexing
    /// Returns a mutable substring
    ///
    /// Although this looks like the IndexingOperationExt trait, it is not
    /// because it returns a string instead of a value
    pub fn mut_substr(&mut self, index: RangeInclusive<&Value>) -> Result<&mut str, crate::Error> {
        let range = self.map_range_to_bytes(index)?;
        self.inner_mut()
            .get_mut(range.start..=range.end)
            .ok_or(Error::Index {
                key: format!("{}..{}", range.start, range.end),
            })
    }

    /// Replace a set of characters in the string
    ///
    /// Although this looks like the IndexingOperationExt trait, it is not
    /// because it returns a string instead of a value
    pub fn set_substr(
        &mut self,
        index: RangeInclusive<&Value>,
        value: Value,
    ) -> Result<(), crate::Error> {
        let range = *Int::try_from((*index.start()).clone())?.inner() as usize
            ..*Int::try_from((*index.end()).clone())?.inner() as usize;

        let value = Str::try_from(value)?.inner().clone();

        let prefix = if range.start == 0 {
            "".to_string()
        } else {
            self.substr(&0.into()..=&(range.start - 1).into())?
                .to_string()
        };

        let char_count = self.inner_mut().chars().count();
        let suffix = if range.end == char_count - 1 {
            ""
        } else {
            self.substr(&(range.end + 1).into()..=&(char_count - 1).into())?
        };

        *self.inner_mut() = format!("{}{}{}", prefix, value, suffix);
        Ok(())
    }

    /// Convert an index value to a range, useful for bridging the gap between
    /// the IndexingOperationExt trait and the substr functions
    /// Can fail if the index is not an array of integers, or if the array is empty
    pub fn index_value_to_range(index: &Value) -> Result<std::ops::RangeInclusive<Value>, Error> {
        // Convert index to a range - we will need an array of integers
        let index = index.as_a::<Array>()?;
        let indices = index
            .inner()
            .iter()
            .map(|v| Ok::<IntInner, Error>(*v.as_a::<Int>()?.inner()))
            .collect::<Result<Vec<_>, _>>()?;
        if indices.is_empty() {
            Err(Error::Index {
                key: index.to_string(),
            })?;
        }

        let start = Value::from(*indices.iter().min().unwrap());
        let end = Value::from(*indices.iter().max().unwrap());
        Ok(start..=end)
    }
}

map_value!(
    from = Str,
    handle_into = Value::String,
    handle_from = |v: Value| match v {
        Value::String(v) => Ok(v),
        _ => Ok(Str::from(v.to_string())),
    }
);

map_type!(Bool, Str);
map_type!(Int, Str);
map_type!(Float, Str);
map_type!(Fixed, Str);
map_type!(Currency, Str);
map_type!(Array, Str);
map_type!(Object, Str);

impl MatchingOperationExt for Str {
    fn matching_op(
        container: &Self,
        pattern: &Value,
        operation: MatchingOperation,
    ) -> Result<Value, crate::Error>
    where
        Self: Sized,
    {
        let pattern = Str::try_from(pattern.clone())?;
        let result = match operation {
            MatchingOperation::Contains => {
                let pattern = pattern.inner().as_str();
                let pattern = convert_regex_string(pattern, |s: String| s)?;
                pattern.is_match(container.inner().as_str())
            }
            MatchingOperation::StartsWith => {
                container.inner().starts_with(pattern.inner().as_str())
            }
            MatchingOperation::EndsWith => container.inner().ends_with(pattern.inner().as_str()),
            MatchingOperation::Matches => {
                let pattern = pattern.inner().as_str();
                let pattern = convert_regex_string(pattern, |mut s: String| {
                    if !s.starts_with('^') {
                        s = "^".to_string() + s.as_str();
                    }
                    if !s.ends_with('$') {
                        s += "$"
                    }
                    s
                })?;
                pattern.is_match(container.inner().as_str())
            }

            // Handled by Value
            _ => false,
        };

        Ok(result.into())
    }
}

impl ArithmeticOperationExt for Str {
    fn arithmetic_op(
        left: &Self,
        right: &Self,
        operation: ArithmeticOperation,
    ) -> Result<Self, crate::Error> {
        let left = left.inner().to_string();
        let right = right.inner().to_string();
        let result = match operation {
            ArithmeticOperation::Add => left + right.as_str(),

            ArithmeticOperation::Subtract => left.replace(&right, ""),

            // reverse string
            ArithmeticOperation::Negate => {
                let mut result = left.clone();
                result = result.chars().rev().collect();
                result
            }

            _ => Err(Error::UnsupportedOperation {
                operation,
                actual_type: ValueType::String,
            })?,
        };
        Ok(result.into())
    }

    fn arithmetic_neg(&self) -> Result<Self, crate::Error>
    where
        Self: Sized,
    {
        Str::arithmetic_op(self, &self.clone(), ArithmeticOperation::Negate)
    }
}

impl BooleanOperationExt for Str {
    fn boolean_op(left: &Self, right: &Self, operation: BooleanOperation) -> Result<Value, Error> {
        let result = match operation {
            BooleanOperation::And => !left.inner().is_empty() && !right.inner().is_empty(),
            BooleanOperation::Or => !left.inner().is_empty() || !right.inner().is_empty(),

            BooleanOperation::LT => *left.inner() < *right.inner(),
            BooleanOperation::GT => *left.inner() > *right.inner(),
            BooleanOperation::LTE => *left.inner() <= *right.inner(),
            BooleanOperation::GTE => *left.inner() >= *right.inner(),
            BooleanOperation::EQ => *left.inner() == *right.inner(),
            BooleanOperation::NEQ => *left.inner() != *right.inner(),
            BooleanOperation::Not => left.inner().is_empty(),
        };

        Ok(result.into())
    }

    fn boolean_not(&self) -> Result<Value, crate::Error>
    where
        Self: Sized,
    {
        Str::boolean_op(self, &self.clone(), BooleanOperation::Not)
    }
}

// This function will convert a string of either forms `/pattern/flags` or `pattern` to a regex object
fn convert_regex_string<F>(input: &str, formatting_callback: F) -> Result<regex::Regex, Error>
where
    F: Fn(String) -> String,
{
    let mut pattern = input.to_string();
    let mut flags = None;

    // Check if the string contains a regex pattern
    if input.starts_with('/') {
        let end = input.rfind('/').unwrap();
        pattern = input[1..end].to_string();
        flags = Some(input[end + 1..].to_string());
    }

    pattern = formatting_callback(pattern);

    let mut regex = regex::RegexBuilder::new(&pattern);
    if let Some(flags) = flags {
        for flag in flags.chars() {
            match flag {
                'i' => regex.case_insensitive(true),
                'm' => regex.multi_line(true),
                's' => regex.dot_matches_new_line(true),
                'U' => regex.swap_greed(true),
                'u' => regex.unicode(true),
                'x' => regex.ignore_whitespace(true),
                _ => &mut regex,
            };
        }
    }

    Ok(regex.build()?)
}

//
// Tests
//

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

    #[test]
    fn test_matching() {
        let result = Str::matching_op(
            &Str::from("Hello, world!"),
            &Str::from("[a-z]").into(),
            MatchingOperation::Contains,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::matching_op(
            &Str::from("Hello, world!"),
            &Str::from("world").into(),
            MatchingOperation::StartsWith,
        )
        .unwrap();
        assert_eq!(result, Bool::from(false).into());

        let result = Str::matching_op(
            &Str::from("Hello, world!"),
            &Str::from("world!").into(),
            MatchingOperation::EndsWith,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::matching_op(
            &Str::from("Hello, world!"),
            &Str::from("Hello, w..ld!").into(),
            MatchingOperation::Matches,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::matching_op(
            &Str::from("Hello, world!"),
            &Str::from("/h.*/i").into(),
            MatchingOperation::Matches,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());
    }

    #[test]
    fn test_indexing() {
        let value_range = Array::from(vec![0.into(), 1.into(), 2.into()]);
        let value_range = Value::from(value_range);
        let value_range = Str::index_value_to_range(&value_range).unwrap();
        let value_range = value_range.start()..=value_range.end();
        assert_eq!(value_range, &0.into()..=&2.into());
        let s = Str::from("012");
        assert_eq!(s.substr(value_range).unwrap(), "012");

        let s = Str::from("012");
        assert_eq!(s.substr(&(-2).into()..=&(-1).into()).unwrap(), "12");

        // normal string
        let s = Str::from("Hello, world!");
        assert_eq!(s.substr(&0.into()..=&1.into()).unwrap(), "He");

        // Bad and scary unicode string, with multibyte chars at the start
        let s = Str::from("👋🌎");
        assert_eq!(s.substr(&0.into()..=&0.into()).unwrap(), "👋");

        let mut s = Str::from("S👋🌎");
        s.set_substr(&1.into()..=&1.into(), "B".into()).unwrap();
        assert_eq!(s, "SB🌎".into());

        let mut s = Str::from("S👋🌎");
        s.set_substr(&0.into()..=&1.into(), "B".into()).unwrap();
        assert_eq!(s, "B🌎".into());

        let mut s = Str::from("S👋🌎");
        s.set_substr(&0.into()..=&0.into(), "B".into()).unwrap();
        assert_eq!(s, "B👋🌎".into());

        let mut s = Str::from("S👋🌎");
        s.set_substr(&2.into()..=&2.into(), "B".into()).unwrap();
        assert_eq!(s, "S👋B".into());
    }

    #[test]
    fn test_arithmetic() {
        let result = Str::arithmetic_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            ArithmeticOperation::Add,
        )
        .unwrap();
        assert_eq!(result, Str::from("Hello, world!"));

        let result = Str::arithmetic_op(
            &Str::from("Hello, world!"),
            &Str::from("d!"),
            ArithmeticOperation::Subtract,
        )
        .unwrap();
        assert_eq!(result, Str::from("Hello, worl"));

        let result = Str::arithmetic_neg(&Str::from("Hello, world!")).unwrap();
        assert_eq!(result, Str::from("!dlrow ,olleH"));

        // now with emojis
        let result = Str::arithmetic_neg(&Str::from("👋🌎")).unwrap();
        assert_eq!(result, Str::from("🌎👋"));
    }

    #[test]
    fn test_boolean_logic() {
        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::And,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::Or,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::LT,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::GT,
        )
        .unwrap();
        assert_eq!(result, Bool::from(false).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::LTE,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::GTE,
        )
        .unwrap();
        assert_eq!(result, Bool::from(false).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::EQ,
        )
        .unwrap();
        assert_eq!(result, Bool::from(false).into());

        let result = Str::boolean_op(
            &Str::from("Hello, "),
            &Str::from("world!"),
            BooleanOperation::NEQ,
        )
        .unwrap();
        assert_eq!(result, Bool::from(true).into());
    }
}