toon-format-rs 0.1.0

Token-Oriented Object Notation (TOON) parser and serializer for Rust
Documentation
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
use crate::error::Result;
use crate::value::Value;
use indexmap::IndexMap;
use std::io::Write;

/// Options for serializing TOON
#[derive(Debug, Clone)]
pub struct SerializeOptions {
    /// Number of spaces per indentation level (default: 2)
    pub indent_size: usize,
    /// Default delimiter for inline arrays (default: comma)
    pub delimiter: Delimiter,
    /// Whether to use tabular format for uniform arrays of objects
    pub use_tabular: bool,
    /// Maximum number of primitive items before switching to expanded array
    pub max_inline_items: usize,
}

impl Default for SerializeOptions {
    fn default() -> Self {
        SerializeOptions {
            indent_size: 2,
            delimiter: Delimiter::Comma,
            use_tabular: true,
            max_inline_items: 10,
        }
    }
}

/// Delimiter types for arrays
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Delimiter {
    /// Comma (,)
    Comma,
    /// Tab (\t)
    Tab,
    /// Pipe (|)
    Pipe,
}

impl Delimiter {
    /// Returns the delimiter character
    pub fn as_char(&self) -> char {
        match self {
            Delimiter::Comma => ',',
            Delimiter::Tab => '\t',
            Delimiter::Pipe => '|',
        }
    }

    /// Returns the delimiter as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            Delimiter::Comma => ",",
            Delimiter::Tab => "\t",
            Delimiter::Pipe => "|",
        }
    }
}

/// Serializes a Value into TOON format
pub struct Serializer<'a> {
    options: &'a SerializeOptions,
    output: Vec<u8>,
}

impl<'a> Serializer<'a> {
    /// Creates a new serializer with the given options
    pub fn new(options: &'a SerializeOptions) -> Self {
        Serializer {
            options,
            output: Vec::new(),
        }
    }

    /// Serializes the value and returns the TOON string
    pub fn serialize(mut self, value: &Value) -> Result<String> {
        self.write_value(value, 0)?;
        String::from_utf8(self.output).map_err(|_| {
            crate::error::Error::InvalidUtf8
        })
    }

    /// Writes a value at the given indentation depth
    fn write_value(&mut self, value: &Value, depth: usize) -> Result<()> {
        match value {
            Value::Null => {
                write!(self.output, "null")?;
            }
            Value::Bool(true) => {
                write!(self.output, "true")?;
            }
            Value::Bool(false) => {
                write!(self.output, "false")?;
            }
            Value::Number(n) => {
                write!(self.output, "{}", n)?;
            }
            Value::String(s) => {
                self.write_string(s)?;
            }
            Value::Array(arr) => {
                self.write_array(arr, depth)?;
            }
            Value::Object(obj) => {
                self.write_object(obj, depth)?;
            }
        }
        Ok(())
    }

    /// Writes a string with quoting only when necessary
    fn write_string(&mut self, s: &str) -> Result<()> {
        if self.needs_quoting(s) {
            write!(self.output, "\"{}\"", self.escape_string(s))?;
        } else {
            write!(self.output, "{}", s)?;
        }
        Ok(())
    }

    /// Checks if a string needs quoting
    fn needs_quoting(&self, s: &str) -> bool {
        if s.is_empty() {
            return true;
        }

        // Check if it looks like a number, boolean, or null
        if s == "true" || s == "false" || s == "null" {
            return true;
        }

        if self.is_numeric(s) {
            return true;
        }

        // Check for special characters or spaces
        let delimiter = self.options.delimiter.as_char();
        let chars_to_quote = [':', ',', '[', ']', '{', '}', '\n', '\r', '\t', '"', '\'', delimiter];

        s.starts_with(' ')
            || s.ends_with(' ')
            || s.starts_with('\t')
            || s.ends_with('\t')
            || s.chars().any(|c| chars_to_quote.contains(&c))
    }

    /// Checks if a string looks like a number
    fn is_numeric(&self, s: &str) -> bool {
        if s.is_empty() {
            return false;
        }

        let mut chars = s.chars().peekable();

        // Optional sign
        if let Some('-') = chars.peek() {
            chars.next();
        }

        // Integer part
        let mut has_digits = false;
        while let Some(c) = chars.peek() {
            if c.is_ascii_digit() {
                has_digits = true;
                chars.next();
            } else {
                break;
            }
        }

        if !has_digits {
            return false;
        }

        // Optional decimal part
        if let Some('.') = chars.peek() {
            chars.next();
            let mut frac_digits = false;
            while let Some(c) = chars.peek() {
                if c.is_ascii_digit() {
                    frac_digits = true;
                    chars.next();
                } else {
                    break;
                }
            }
            if !frac_digits {
                return false;
            }
        }

        // Optional exponent
        if let Some('e') | Some('E') = chars.peek() {
            chars.next();
            if let Some('+') | Some('-') = chars.peek() {
                chars.next();
            }
            let mut exp_digits = false;
            while let Some(c) = chars.peek() {
                if c.is_ascii_digit() {
                    exp_digits = true;
                    chars.next();
                } else {
                    break;
                }
            }
            if !exp_digits {
                return false;
            }
        }

        chars.peek().is_none()
    }

    /// Escapes special characters in a string
    fn escape_string(&self, s: &str) -> String {
        s.replace('\\', "\\\\")
            .replace('"', "\\\"")
            .replace('\n', "\\n")
            .replace('\r', "\\r")
            .replace('\t', "\\t")
    }

    /// Writes an array
    fn write_array(&mut self, arr: &[Value], depth: usize) -> Result<()> {
        if arr.is_empty() {
            // Write empty array as []
            write!(self.output, "[]")?;
            return Ok(());
        }

        // Check if all elements are objects with the same keys (uniform)
        if self.options.use_tabular && self.is_uniform_object_array(arr) {
            self.write_tabular_array(arr, depth)?;
        } else if arr.len() <= self.options.max_inline_items
            && arr.iter().all(|v| self.is_primitive(v))
        {
            // Inline primitive array
            self.write_inline_primitive_array(arr)?;
        } else {
            // Expanded array with hyphens
            self.write_expanded_array(arr, depth)?;
        }

        Ok(())
    }

    /// Checks if all elements are objects with identical keys
    fn is_uniform_object_array(&self, arr: &[Value]) -> bool {
        if arr.len() < 2 {
            return false;
        }

        let first = match &arr[0] {
            Value::Object(obj) => obj,
            _ => return false,
        };

        let keys: Vec<_> = first.keys().collect();

        for item in arr.iter().skip(1) {
            match item {
                Value::Object(obj) => {
                    if obj.len() != keys.len() {
                        return false;
                    }
                    for (i, key) in keys.iter().enumerate() {
                        if obj.keys().nth(i) != Some(*key) {
                            return false;
                        }
                    }
                }
                _ => return false,
            }
        }

        true
    }

    /// Checks if a value is a primitive (not object or array)
    fn is_primitive(&self, value: &Value) -> bool {
        !matches!(value, Value::Object(_) | Value::Array(_))
    }

    /// Writes a tabular array
    fn write_tabular_array(&mut self, arr: &[Value], depth: usize) -> Result<()> {
        self.write_expanded_array(arr, depth)
    }

    /// Writes an expanded array with hyphens
    fn write_expanded_array(&mut self, arr: &[Value], depth: usize) -> Result<()> {
        let indent = self.make_indent(depth);

        for item in arr {
            write!(self.output, "\n{}", indent)?;
            write!(self.output, "- ")?;
            self.write_value_inline(item)?;
        }
        Ok(())
    }

    /// Writes an inline primitive array
    fn write_inline_primitive_array(&mut self, arr: &[Value]) -> Result<()> {
        let delim = self.options.delimiter.as_str();

        for (i, item) in arr.iter().enumerate() {
            if i > 0 {
                write!(self.output, "{}", delim)?;
            }
            self.write_value_inline(item)?;
        }
        Ok(())
    }

    /// Writes a value inline (without indentation)
    fn write_value_inline(&mut self, value: &Value) -> Result<()> {
        match value {
            Value::Null => {
                write!(self.output, "null")?;
            }
            Value::Bool(true) => {
                write!(self.output, "true")?;
            }
            Value::Bool(false) => {
                write!(self.output, "false")?;
            }
            Value::Number(n) => {
                write!(self.output, "{}", n)?;
            }
            Value::String(s) => {
                self.write_string(s)?;
            }
            Value::Array(arr) => {
                write!(self.output, "[")?;
                for (i, item) in arr.iter().enumerate() {
                    if i > 0 {
                        write!(self.output, ", ")?;
                    }
                    self.write_value_inline(item)?;
                }
                write!(self.output, "]")?;
            }
            Value::Object(obj) => {
                write!(self.output, "{{")?;
                for (i, (k, v)) in obj.iter().enumerate() {
                    if i > 0 {
                        write!(self.output, ", ")?;
                    }
                    self.write_string(k)?;
                    write!(self.output, ": ")?;
                    self.write_value_inline(v)?;
                }
                write!(self.output, "}}")?;
            }
        }
        Ok(())
    }

    /// Writes an object
    fn write_object(&mut self, obj: &IndexMap<String, Value>, depth: usize) -> Result<()> {
        if obj.is_empty() {
            return Ok(());
        }

        let indent = self.make_indent(depth);

        for (i, (key, value)) in obj.iter().enumerate() {
            if i > 0 || depth > 0 {
                write!(self.output, "\n")?;
            }
            write!(self.output, "{}", indent)?;

            // Check if value is a uniform array of objects (for tabular format)
            let is_tabular = if let Value::Array(arr) = value {
                self.options.use_tabular && self.is_uniform_object_array(arr)
            } else {
                false
            };

            self.write_string(key)?;

            if is_tabular {
                if let Value::Array(arr) = value {
                    self.write_tabular_array_header(arr, depth)?;
                }
            } else {
                write!(self.output, ":")?;

                if let Value::Array(arr) = value {
                    if arr.is_empty() {
                        write!(self.output, " []")?;
                    } else if arr.len() <= self.options.max_inline_items
                        && arr.iter().all(|v| self.is_primitive(v))
                    {
                        // Inline array header
                        write!(self.output, " [{}]: ", arr.len())?;
                        self.write_inline_primitive_array(arr)?;
                    } else {
                        self.write_expanded_array_value(arr, depth + 1)?;
                    }
                } else if value.is_object() {
                    self.write_nested_object(value, depth + 1)?;
                } else {
                    write!(self.output, " ")?;
                    self.write_value_inline(value)?;
                }
            }
        }

        Ok(())
    }

    /// Writes a tabular array header and rows
    fn write_tabular_array_header(&mut self, arr: &[Value], depth: usize) -> Result<()> {
        let first = arr[0].as_object().unwrap();
        let keys: Vec<_> = first.keys().cloned().collect();
        let length = arr.len();

        write!(self.output, "[{}]{{", length)?;
        for (i, key) in keys.iter().enumerate() {
            if i > 0 {
                write!(self.output, ",")?;
            }
            write!(self.output, "{}", key)?;
        }
        write!(self.output, "}}:")?;

        // Write rows
        let row_indent = self.make_indent(depth + 1);
        let delim = self.options.delimiter.as_str();

        for row in arr {
            write!(self.output, "\n{}", row_indent)?;
            let obj = row.as_object().unwrap();
            for (i, key) in keys.iter().enumerate() {
                if i > 0 {
                    write!(self.output, "{}", delim)?;
                }
                let val = obj.get(key).unwrap();
                self.write_value_inline(val)?;
            }
        }
        Ok(())
    }

    /// Writes an expanded array as a value (with proper indentation)
    fn write_expanded_array_value(&mut self, arr: &[Value], depth: usize) -> Result<()> {
        let indent = self.make_indent(depth);

        for item in arr {
            write!(self.output, "\n{}", indent)?;
            write!(self.output, "- ")?;
            self.write_value_inline(item)?;
        }
        Ok(())
    }

    /// Writes a nested object
    fn write_nested_object(&mut self, value: &Value, depth: usize) -> Result<()> {
        if let Value::Object(obj) = value {
            let indent = self.make_indent(depth);

            for (_i, (key, val)) in obj.iter().enumerate() {
                write!(self.output, "\n{}", indent)?;
                self.write_string(key)?;
                write!(self.output, ":")?;

                if val.is_object() {
                    self.write_nested_object(val, depth + 1)?;
                } else if let Value::Array(arr) = val {
                    if arr.is_empty() {
                        write!(self.output, " []")?;
                    } else if arr.len() <= self.options.max_inline_items
                        && arr.iter().all(|v| self.is_primitive(v))
                    {
                        write!(self.output, " [{}]: ", arr.len())?;
                        self.write_inline_primitive_array(arr)?;
                    } else {
                        self.write_expanded_array_value(arr, depth + 1)?;
                    }
                } else {
                    write!(self.output, " ")?;
                    self.write_value_inline(val)?;
                }
            }
        }
        Ok(())
    }

    /// Creates an indentation string
    fn make_indent(&self, depth: usize) -> String {
        " ".repeat(depth * self.options.indent_size)
    }
}

/// Serializes a Value into TOON string with default options
pub fn to_string(value: &Value) -> Result<String> {
    let options = SerializeOptions::default();
    let serializer = Serializer::new(&options);
    serializer.serialize(value)
}

/// Serializes a Value into TOON string with custom options
pub fn to_string_pretty(value: &Value, options: &SerializeOptions) -> Result<String> {
    let serializer = Serializer::new(options);
    serializer.serialize(value)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::Value;
    use indexmap::IndexMap;

    #[test]
    fn test_serialize_simple_object() {
        let mut obj = IndexMap::new();
        obj.insert("id".to_string(), Value::integer(123));
        obj.insert("name".to_string(), Value::string("Alice"));
        obj.insert("active".to_string(), Value::Bool(true));

        let value = Value::Object(obj);
        let result = to_string(&value).unwrap();

        assert!(result.contains("id: 123"));
        assert!(result.contains("name: Alice"));
        assert!(result.contains("active: true"));
    }

    #[test]
    fn test_serialize_array_inline() {
        let value = Value::Array(vec![
            Value::string("foo"),
            Value::string("bar"),
            Value::string("baz"),
        ]);

        let result = to_string(&value).unwrap();
        assert_eq!(result, "foo,bar,baz");
    }

    #[test]
    fn test_serialize_tabular_array() {
        let mut row1 = IndexMap::new();
        row1.insert("id".to_string(), Value::integer(1));
        row1.insert("name".to_string(), Value::string("Alice"));
        row1.insert("role".to_string(), Value::string("admin"));

        let mut row2 = IndexMap::new();
        row2.insert("id".to_string(), Value::integer(2));
        row2.insert("name".to_string(), Value::string("Bob"));
        row2.insert("role".to_string(), Value::string("user"));

        let mut obj = IndexMap::new();
        obj.insert(
            "users".to_string(),
            Value::Array(vec![Value::Object(row1), Value::Object(row2)]),
        );

        let value = Value::Object(obj);
        let result = to_string(&value).unwrap();

        assert!(result.contains("users[2]{id,name,role}:"));
        assert!(result.contains("1,Alice,admin"));
        assert!(result.contains("2,Bob,user"));
    }

    #[test]
    fn test_string_quoting() {
        let mut obj = IndexMap::new();
        obj.insert("msg".to_string(), Value::string("hello, world"));
        obj.insert("path".to_string(), Value::string("/home/user"));

        let value = Value::Object(obj);
        let result = to_string(&value).unwrap();

        assert!(result.contains("\"hello, world\""));
        assert!(result.contains("path: /home/user"));
    }

    #[test]
    fn test_serialize_nested_object() {
        let mut inner = IndexMap::new();
        inner.insert("id".to_string(), Value::integer(1));
        inner.insert("name".to_string(), Value::string("Alice"));

        let mut obj = IndexMap::new();
        obj.insert("user".to_string(), Value::Object(inner));

        let value = Value::Object(obj);
        let result = to_string(&value).unwrap();

        assert!(result.contains("user:"));
        assert!(result.contains("  id: 1"));
        assert!(result.contains("  name: Alice"));
    }
}