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
use std::fmt::Display;
use std::fs::File;
use std::io::{Error, ErrorKind, Result, Write};
use std::path::Path;

///
/// JSON serializer with eXtra Small memory footprint.
/// Very immature, experimental code.
/// The main idea is that application data structure is NOT duplicated into another one, just for the purpose of saving JSON.
/// Instead, JSON is generated by calls to this api, and client is responsible for making calls in proper sequence. JsonFx only helps with basic stuff like tokenization.
///
/// TODO: add automatic scope closing (and make it the only way to close level)
///
pub struct JsonXsSerializer<'a> {
    writer: Box<dyn Write + 'a>,
    levels: Vec<Level>,
}

struct Level {
    /// number of completed elements
    size: usize,
    /// collection type
    ctype: CollectionType,
}

enum CollectionType {
    JsonArray,
    JsonObject {
        /// the key under construction, if value is collection
        key: JsonXsValue
    },
}


/// JSON typed value representation.
#[derive(Clone)]
pub enum JsonXsValue/*<'a>*/ {
    Null,
    Bool(bool),
    Int(i64),
    Unsigned(u64),
    Decimal(f64),
    String(String),
    // TODO/nice: Str(&'a str),

    /// only for use in `key` param - to indicate array element, not object
    NA,
}

impl Display for JsonXsValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JsonXsValue::NA => Ok(()),
            JsonXsValue::Null => write!(f, "null"),
            JsonXsValue::Bool(value) => write!(f, "{}", value),
            JsonXsValue::Int(value) => write!(f, "{}", value),
            JsonXsValue::Unsigned(value) => write!(f, "{}", value),
            JsonXsValue::Decimal(value) => write!(f, "{}", value),
            JsonXsValue::String(value) => write!(f, "\"{}\"", value
                .replace("\\", "\\\\")
                .replace("\n", "\\n")
                .replace("\"", "\\\"")), // TODO this escaping is insufficient
        }
    }
}

impl JsonXsSerializer<'_> {
    pub fn use_stdout() -> Self {
        let writer = Box::new(std::io::stdout());
        JsonXsSerializer { writer, levels: vec![] }
    }

    pub fn use_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let writer = Box::new(File::create(path)?);
        Ok(JsonXsSerializer { writer, levels: vec![] })
    }

    pub fn done(&mut self) -> Result<()> {
        self.writer.flush()?;
        if !self.levels.is_empty() {
            return Err(Error::new(ErrorKind::InvalidData, "Not empty!"));
        }
        Ok(())
    }

    pub fn open_obj<K: Into<JsonXsValue>+Clone>(&mut self, key: K) -> Result<()> {
        self.val_start()?;
        self.obj_key(key.clone())?;
        self.writer.write(b"{")?;
        self.levels.push(Level {
            size: 0,
            ctype: CollectionType::JsonObject { key: key.into() },
        });
        Ok(())
    }

    pub fn open_array<K: Into<JsonXsValue>>(&mut self, key: K) -> Result<()> {
        self.val_start()?;
        self.obj_key(key)?;
        self.writer.write(b"[")?;
        self.levels.push(Level {
            size: 0,
            ctype: CollectionType::JsonArray,
        });
        Ok(())
    }

    pub fn close(&mut self) -> Result<()> {
        match self.levels.pop() {
            None => Err(Error::new(ErrorKind::InvalidData, "no collection to close")),
            Some(level) => {
                match level.ctype {
                    CollectionType::JsonArray => {
                        self.writer.write(b"]")
                    }
                    CollectionType::JsonObject { key:_ } => {
                        self.writer.write(b"}")
                    }
                }
            }
        }?;
        self.val_end()
    }

    /// extremely minimalistic indentation
    fn indent(&mut self) -> Result<()> {
        self.writer.write(b"\n")?;
        for _ in &self.levels {
            self.writer.write(b"\t")?;
        }
        Ok(())
    }

    fn val_start(&mut self) -> Result<()> {
        let elem_separator =
            match self.levels.last() {
                Some(top) => top.size > 0,
                None => false
            };
        if elem_separator {
            self.writer.write(b",")?;
        }
        self.indent()?;
        Ok(())
    }

    fn val_end(&mut self) -> Result<()> {
        match self.levels.last_mut() {
            Some(top) => top.size += 1,
            None => {}
        }
        Ok(())
    }

    fn obj_key<K: Into<JsonXsValue>>(&mut self, key: K) -> Result<()> {
        let ki = key.into();
        let key_str = &ki.to_string();
        match ki.clone() {
            JsonXsValue::NA => {
                match self.levels.last() {
                    None => {},
                    Some(level) => match &level.ctype {
                        CollectionType::JsonArray => {},
                        CollectionType::JsonObject { .. } => Err(Error::new(ErrorKind::InvalidData, "object element must have key"))?
                    },
                }
            },
            _ => {
                match self.levels.last_mut() {
                    None => Err(Error::new(ErrorKind::InvalidData, "top-level element cannot have key"))?,
                    Some(level) => match &mut level.ctype {
                        CollectionType::JsonArray => Err(Error::new(ErrorKind::InvalidData, "array element cannot have key"))?,
                        CollectionType::JsonObject { key } => *key = ki, // TODO: use for tracking, in close
                    },
                }
                self.writer.write(key_str.as_bytes())?;
                self.writer.write(b":")?;
            },
        }
        Ok(())
    }

    pub fn element<K: Into<JsonXsValue>,V: Into<JsonXsValue>> (&mut self, key: K, value: V) -> Result<()> {
        self.val_start()?;
        self.obj_key(key)?;
        let v = value.into();
        self.writer.write(v.to_string().as_bytes())?;
        self.val_end()
    }
}

impl Into<JsonXsValue> for String {
    fn into(self) -> JsonXsValue { JsonXsValue::String(self.to_string()) }
}

impl Into<JsonXsValue> for &String {
    fn into(self) -> JsonXsValue { JsonXsValue::String(self.to_string()) }
}
impl Into<JsonXsValue> for &str {
    fn into(self) -> JsonXsValue { JsonXsValue::String(self.to_string()) }
}
impl Into<JsonXsValue> for usize {
    fn into(self) -> JsonXsValue { JsonXsValue::Unsigned(self as u64) }
}
impl Into<JsonXsValue> for &i32 {
    fn into(self) -> JsonXsValue { JsonXsValue::Int(*self as i64) }
}
impl Into<JsonXsValue> for &i64 {
    fn into(self) -> JsonXsValue { JsonXsValue::Int(*self) }
}
impl Into<JsonXsValue> for &f32 {
    fn into(self) -> JsonXsValue { JsonXsValue::Decimal(*self as f64) }
}
impl Into<JsonXsValue> for &f64 {
    fn into(self) -> JsonXsValue { JsonXsValue::Decimal(*self) }
}

#[cfg(test)]
mod tests {
    use std::io::{Result, Write};

    use crate::jsonxs::JsonXsValue;

    use super::JsonXsSerializer;

    struct MyBuf {
        bytes: Vec<u8>,
    }

    impl MyBuf {
        fn collected_output(&self) -> String {
            std::str::from_utf8(self.bytes.as_slice()).unwrap().to_string()
        }
    }

    impl Write for MyBuf {
        fn write(&mut self, buf: &[u8]) -> Result<usize> {
            self.bytes.write(buf)
        }

        fn flush(&mut self) -> Result<()> {
            self.bytes.flush()
        }
    }

    #[test]
    fn test_object_empty() {
        let mut bb = MyBuf { bytes: vec![] };
        let bw = Box::new(&mut bb);
        {
            // let mut ser = JsonXsSerializer::use_stdout();
            let mut ser = JsonXsSerializer { writer: bw, levels: Default::default() };
            ser.open_obj(JsonXsValue::NA).unwrap();
            ser.close().unwrap();
            ser.done().unwrap();
        }
        //todo check output
        println!("TEST OK: {}", bb.collected_output());
    }

    #[test]
    fn test_array_empty() {
        let mut ser = JsonXsSerializer::use_stdout();
        ser.open_array(JsonXsValue::NA).unwrap();
        ser.close().unwrap();
        ser.done().unwrap();
        println!("TEST OK");
    }
}