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
extern crate skimmer;

use crate::model::{EncodedString, Model, Node, Renderer, Rope, Tagged, TaggedValue};

use std::any::Any;
use std::borrow::Cow;
use std::iter::Iterator;

pub static TAG: &'static str = "tag:yamlette.org,1:literal";

#[derive(Copy, Clone, Debug)]
pub struct Literal;

impl Literal {
    pub fn get_tag() -> Cow<'static, str> {
        Cow::from(TAG)
    }

    #[inline(always)]
    pub fn bytes_to_string(&self, bytes: &[u8]) -> Result<String, ()> {
        match String::from_utf8(Vec::from(bytes)) {
            Ok(s) => Ok(s),
            _ => Err(()),
        }
    }

    pub fn bytes_to_string_times(&self, bytes: &[u8], times: usize) -> Result<String, ()> {
        let mut vec: Vec<u8> = Vec::with_capacity(bytes.len() * times);

        for _ in 0..times {
            vec.extend(bytes);
        }

        match String::from_utf8(vec) {
            Ok(s) => Ok(s),
            _ => Err(()),
        }
    }

    #[inline(always)]
    pub fn string_to_bytes(&self, string: String) -> Vec<u8> {
        string.into_bytes()
    }
}

impl Model for Literal {
    fn get_tag(&self) -> Cow<'static, str> {
        Self::get_tag()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mut_any(&mut self) -> &mut dyn Any {
        self
    }

    // fn get_encoding (&self) -> Encoding { self.encoding }

    fn is_decodable(&self) -> bool {
        true
    }

    fn is_encodable(&self) -> bool {
        true
    }

    fn has_default(&self) -> bool {
        true
    }

    fn get_default(&self) -> TaggedValue {
        TaggedValue::from(LiteralValue {
            value: Cow::from(String::with_capacity(0)),
        })
    }

    fn encode(
        &self,
        _renderer: &Renderer,
        value: TaggedValue,
        _tags: &mut dyn Iterator<Item = &(Cow<'static, str>, Cow<'static, str>)>,
    ) -> Result<Rope, TaggedValue> {
        match <TaggedValue as Into<Result<LiteralValue, TaggedValue>>>::into(value) {
            Ok(value) => match value.value {
                Cow::Owned(s) => Ok(Rope::from(Node::String(EncodedString::from(
                    s.into_bytes(),
                )))),
                Cow::Borrowed(s) => Ok(Rope::from(Node::String(EncodedString::from(s.as_bytes())))),
            },
            Err(value) => Err(value),
        }
    }

    fn decode(&self, _: bool, value: &[u8]) -> Result<TaggedValue, ()> {
        let string = self.bytes_to_string(value)?;
        Ok(TaggedValue::from(LiteralValue::from(string)))
    }
}

#[derive(Debug)]
pub struct LiteralValue {
    value: Cow<'static, str>,
}

impl Tagged for LiteralValue {
    fn get_tag(&self) -> Cow<'static, str> {
        Cow::from(TAG)
    }

    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn as_mut_any(&mut self) -> &mut dyn Any {
        self as &mut dyn Any
    }
}

impl From<String> for LiteralValue {
    fn from(value: String) -> LiteralValue {
        LiteralValue {
            value: Cow::from(value),
        }
    }
}

impl From<&'static str> for LiteralValue {
    fn from(value: &'static str) -> LiteralValue {
        LiteralValue {
            value: Cow::from(value),
        }
    }
}

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

#[cfg(all(test, not(feature = "dev")))]
mod tests {
    use super::*;

    use crate::model::{Renderer, Tagged};

    use std::iter;

    #[test]
    fn tag() {
        let literal = Literal;

        assert_eq!(literal.get_tag().as_ref(), TAG);
    }

    #[test]
    fn encode() {
        let renderer = Renderer;
        let literal = Literal;

        let ops = [
            (r#""Hey, this is a string!""#, r#""Hey, this is a string!""#),
            (
                r#""Hey,\nthis is\tanother\" one""#,
                r#""Hey,\nthis is\tanother\" one""#,
            ),
        ];

        for i in 0..ops.len() {
            if let Ok(rope) = literal.encode(
                &renderer,
                TaggedValue::from(LiteralValue::from(ops[i].0.to_string())),
                &mut iter::empty(),
            ) {
                let vec = rope.render(&renderer);
                assert_eq!(vec, ops[i].1.to_string().into_bytes().to_vec());
            } else {
                assert!(false)
            }

            if let Ok(rope) = literal.encode(
                &renderer,
                TaggedValue::from(LiteralValue::from(ops[i].0)),
                &mut iter::empty(),
            ) {
                let vec = rope.render(&renderer);
                assert_eq!(vec, ops[i].1.to_string().into_bytes().to_vec());
            } else {
                assert!(false)
            }
        }
    }

    #[test]
    fn decode() {
        let literal = Literal;

        let ops = [
            ("Hey, this is a string!", "Hey, this is a string!"),
            (r"'Hey, that\'s the string!'", r"'Hey, that\'s the string!'"),
            (
                r#""Hey,\n\ that's\tthe\0string\\""#,
                r#""Hey,\n\ that's\tthe\0string\\""#,
            ),
            (
                r#""This\x0Ais\x09a\x2c\x20test""#,
                r#""This\x0Ais\x09a\x2c\x20test""#,
            ),
            (
                r#""\u0422\u0435\u0441\u0442\x0a""#,
                r#""\u0422\u0435\u0441\u0442\x0a""#,
            ),
            (r#""\u30c6\u30b9\u30c8\x0a""#, r#""\u30c6\u30b9\u30c8\x0a""#),
            (
                r#""\U00013000\U00013001\U00013002\U00013003\U00013004\U00013005\U00013006\U00013007""#,
                r#""\U00013000\U00013001\U00013002\U00013003\U00013004\U00013005\U00013006\U00013007""#,
            ),
        ];

        for i in 0..ops.len() {
            if let Ok(value) = literal.decode(false, ops[i].0.as_bytes()) {
                assert_eq!(value.get_tag(), Cow::from(TAG));

                let val: &str = value
                    .as_any()
                    .downcast_ref::<LiteralValue>()
                    .unwrap()
                    .as_ref();

                assert_eq!(val, ops[i].1);
            } else {
                assert!(false)
            }
        }
    }
}