sphinx/runtime/types/
string.rs

1use core::fmt::Write;
2use crate::runtime::Variant;
3use crate::runtime::strings::{StringValue, StrBuffer};
4use crate::runtime::types::{Type, MetaObject};
5use crate::runtime::errors::{ExecResult};
6
7
8impl MetaObject for StringValue {
9    fn type_tag(&self) -> Type { Type::String }
10    
11    fn len(&self) -> Option<ExecResult<usize>> {
12        Some(Ok(self.char_count()))
13    }
14    
15    fn op_add(&self, rhs: &Variant) -> Option<ExecResult<Variant>> {
16        if let Some(rhs) = rhs.as_strval() {
17            return Some(self.concat(&rhs).map(Variant::from))
18        }
19        None
20    }
21    
22    fn op_radd(&self, lhs: &Variant) -> Option<ExecResult<Variant>> {
23        if let Some(lhs) = lhs.as_strval() {
24            return Some(lhs.concat(self).map(Variant::from))
25        }
26        None
27    }
28    
29    fn cmp_eq(&self, other: &Variant) -> Option<ExecResult<bool>> {
30        if let Some(other) = other.as_strval() {
31            return Some(Ok(*self == other))
32        }
33        None
34    }
35    
36    fn cmp_lt(&self, other: &Variant) -> Option<ExecResult<bool>> {
37        if let Some(other) = other.as_strval() {
38            return Some(Ok(*self < other))
39        }
40        None
41    }
42    
43    fn cmp_le(&self, other: &Variant) -> Option<ExecResult<bool>> {
44        if let Some(other) = other.as_strval() {
45            return Some(Ok(*self <= other))
46        }
47        None
48    }
49    
50    fn fmt_repr(&self) -> ExecResult<StringValue> {
51        let mut buf = StrBuffer::<64>::new();
52        if write!(buf, "\"{}\"", self).is_ok() {
53            Ok(StringValue::new_uninterned(buf))
54        } else {
55            // resort to allocated buffer
56            Ok(StringValue::new_uninterned(format!("\"{}\"", self)))
57        }
58    }
59}