toonconv 0.1.0

A Rust CLI tool for converting JSON to TOON (Token-Oriented Object Notation) format
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
//! Mixed-type array formatting for TOON
//!
//! Handles arrays with heterogeneous element types, providing
//! appropriate formatting based on content variety.

use crate::conversion::ConversionConfig;
use crate::error::{FormattingError, FormattingResult};
use serde_json::Value;

/// Mixed array formatter for heterogeneous arrays
pub struct MixedArrayFormatter<'a> {
    config: &'a ConversionConfig,
    indent_level: usize,
}

impl<'a> MixedArrayFormatter<'a> {
    /// Create a new mixed array formatter
    pub fn new(config: &'a ConversionConfig) -> Self {
        Self {
            config,
            indent_level: 0,
        }
    }

    /// Set the current indentation level
    pub fn set_indent_level(&mut self, level: usize) {
        self.indent_level = level;
    }

    /// Format a mixed-type array
    pub fn format_mixed_array(&mut self, array: &[Value]) -> FormattingResult<String> {
        if array.is_empty() {
            return Ok("[]".to_string());
        }

        // Analyze array content
        let analysis = self.analyze_array(array);

        // Choose formatting strategy based on content
        match analysis.array_type {
            ArrayType::AllPrimitives => self.format_primitive_array(array),
            ArrayType::AllObjects => self.format_object_array(array),
            ArrayType::AllArrays => self.format_nested_arrays(array),
            ArrayType::Mixed => self.format_truly_mixed_array(array),
        }
    }

    /// Analyze array content to determine type distribution
    fn analyze_array(&self, array: &[Value]) -> ArrayAnalysis {
        let mut null_count = 0;
        let mut bool_count = 0;
        let mut number_count = 0;
        let mut string_count = 0;
        let mut array_count = 0;
        let mut object_count = 0;

        for value in array {
            match value {
                Value::Null => null_count += 1,
                Value::Bool(_) => bool_count += 1,
                Value::Number(_) => number_count += 1,
                Value::String(_) => string_count += 1,
                Value::Array(_) => array_count += 1,
                Value::Object(_) => object_count += 1,
            }
        }

        let primitive_count = null_count + bool_count + number_count + string_count;
        let total = array.len();

        // Determine array type
        let array_type = if object_count == total {
            ArrayType::AllObjects
        } else if array_count == total {
            ArrayType::AllArrays
        } else if primitive_count == total {
            ArrayType::AllPrimitives
        } else {
            ArrayType::Mixed
        };

        ArrayAnalysis {
            array_type,
            total_elements: total,
            null_count,
            bool_count,
            number_count,
            string_count,
            array_count,
            object_count,
        }
    }

    /// Format array of primitives (numbers, strings, booleans, nulls)
    fn format_primitive_array(&mut self, array: &[Value]) -> FormattingResult<String> {
        let mut values = Vec::with_capacity(array.len());

        for value in array {
            let formatted = self.format_primitive_value(value)?;
            values.push(formatted);
        }

        let delimiter = self.config.delimiter.as_str();

        if self.config.pretty {
            let mut result = String::new();
            result.push('[');

            for (i, value_str) in values.iter().enumerate() {
                if i > 0 {
                    result.push_str(delimiter);
                    result.push(' ');
                }
                result.push_str(value_str);
            }

            result.push(']');
            Ok(result)
        } else {
            Ok(format!("[{}]", values.join(delimiter)))
        }
    }

    /// Format array of objects
    fn format_object_array(&mut self, array: &[Value]) -> FormattingResult<String> {
        let mut result = String::new();
        result.push('[');

        if self.config.pretty {
            result.push('\n');
        }

        for (i, value) in array.iter().enumerate() {
            if i > 0 {
                result.push(',');
                if self.config.pretty {
                    result.push('\n');
                } else {
                    result.push(' ');
                }
            }

            if self.config.pretty {
                self.indent_level += 1;
                result.push_str(&self.get_indent());
            }

            let formatted = self.format_complex_value(value)?;
            result.push_str(&formatted);

            if self.config.pretty {
                self.indent_level -= 1;
            }
        }

        if self.config.pretty {
            result.push('\n');
            result.push_str(&self.get_indent());
        }

        result.push(']');
        Ok(result)
    }

    /// Format array of arrays
    fn format_nested_arrays(&mut self, array: &[Value]) -> FormattingResult<String> {
        let mut result = String::new();
        result.push('[');

        for (i, value) in array.iter().enumerate() {
            if i > 0 {
                result.push_str(", ");
            }

            let formatted = if let Value::Array(inner) = value {
                self.format_mixed_array(inner)?
            } else {
                return Err(FormattingError::invalid_structure(
                    "Expected array in nested array".to_string(),
                ));
            };

            result.push_str(&formatted);
        }

        result.push(']');
        Ok(result)
    }

    /// Format truly mixed array with different types
    fn format_truly_mixed_array(&mut self, array: &[Value]) -> FormattingResult<String> {
        let mut result = String::new();
        result.push('[');

        if self.config.pretty {
            result.push('\n');
        }

        for (i, value) in array.iter().enumerate() {
            if i > 0 {
                result.push(',');
                if self.config.pretty {
                    result.push('\n');
                } else {
                    result.push(' ');
                }
            }

            if self.config.pretty {
                self.indent_level += 1;
                result.push_str(&self.get_indent());
            }

            // Format based on value type
            let formatted = if value.is_object() || value.is_array() {
                self.format_complex_value(value)?
            } else {
                self.format_primitive_value(value)?
            };

            result.push_str(&formatted);

            if self.config.pretty {
                self.indent_level -= 1;
            }
        }

        if self.config.pretty {
            result.push('\n');
            result.push_str(&self.get_indent());
        }

        result.push(']');
        Ok(result)
    }

    /// Format a primitive value
    fn format_primitive_value(&self, value: &Value) -> FormattingResult<String> {
        match value {
            Value::Null => Ok("null".to_string()),
            Value::Bool(b) => Ok(b.to_string()),
            Value::Number(n) => self.format_number(n),
            Value::String(s) => self.format_string(s),
            _ => Err(FormattingError::invalid_structure(
                "Expected primitive value".to_string(),
            )),
        }
    }

    /// Format a complex value (object or array)
    fn format_complex_value(&mut self, value: &Value) -> FormattingResult<String> {
        match value {
            Value::Object(obj) => {
                // Simple inline object formatting for mixed arrays
                let mut result = String::new();
                result.push('{');

                let mut first = true;
                for (key, val) in obj {
                    if !first {
                        result.push(',');
                        result.push(' ');
                    }
                    first = false;

                    result.push_str(key);
                    result.push(':');
                    result.push(' ');

                    let formatted = self.format_primitive_value(val)?;
                    result.push_str(&formatted);
                }

                result.push('}');
                Ok(result)
            }
            Value::Array(arr) => self.format_mixed_array(arr),
            _ => self.format_primitive_value(value),
        }
    }

    /// Format a number value
    fn format_number(&self, value: &serde_json::Number) -> FormattingResult<String> {
        if let Some(f) = value.as_f64() {
            if f.is_infinite() {
                return Err(FormattingError::invalid_structure(
                    "Infinite numbers are not supported in TOON".to_string(),
                ));
            }
            if f.is_nan() {
                return Err(FormattingError::invalid_structure(
                    "NaN values are not supported in TOON".to_string(),
                ));
            }
        }
        Ok(value.to_string())
    }

    /// Format a string value with smart quoting
    fn format_string(&self, value: &str) -> FormattingResult<String> {
        use super::quotes::QuoteEngine;
        use crate::conversion::QuoteStrategy;

        let engine = QuoteEngine::new(self.config.delimiter.as_str().to_string());

        match self.config.quote_strings {
            QuoteStrategy::Always => engine.quote(value),
            QuoteStrategy::Never => Ok(value.to_string()),
            QuoteStrategy::Smart => engine.format(value),
        }
    }

    /// Get current indentation string
    fn get_indent(&self) -> String {
        " ".repeat(self.indent_level * self.config.indent_size as usize)
    }
}

/// Array type classification
#[derive(Debug, PartialEq)]
enum ArrayType {
    AllPrimitives,
    AllObjects,
    AllArrays,
    Mixed,
}

/// Array content analysis result
#[derive(Debug)]
struct ArrayAnalysis {
    array_type: ArrayType,
    total_elements: usize,
    null_count: usize,
    bool_count: usize,
    number_count: usize,
    string_count: usize,
    array_count: usize,
    object_count: usize,
}

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

    #[test]
    fn test_all_primitives_array() {
        let config = ConversionConfig::default();
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([1, 2, 3, "hello", true, null]);
        let result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();

        assert!(result.starts_with('['));
        assert!(result.ends_with(']'));
        assert!(result.contains("hello"));
    }

    #[test]
    fn test_all_objects_array() {
        let config = ConversionConfig::default();
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([
            {"name": "Alice", "age": 30},
            {"name": "Bob", "age": 25}
        ]);

        let result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();
        assert!(result.contains("Alice"));
        assert!(result.contains("Bob"));
    }

    #[test]
    fn test_nested_arrays() {
        let config = ConversionConfig::default();
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([[1, 2], [3, 4], [5, 6]]);
        let result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();

        assert!(result.starts_with('['));
        assert!(result.contains("[1"));
        assert!(result.contains("[3"));
    }

    #[test]
    fn test_truly_mixed_array() {
        let config = ConversionConfig::default();
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([
            42,
            "hello",
            {"key": "value"},
            [1, 2, 3],
            true,
            null
        ]);

        let result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();
        assert!(result.contains("42"));
        assert!(result.contains("hello"));
        assert!(result.contains("key"));
        assert!(result.contains("true"));
        assert!(result.contains("null"));
    }

    #[test]
    fn test_empty_array() {
        let config = ConversionConfig::default();
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([]);
        let result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();
        assert_eq!(result, "[]");
    }

    #[test]
    fn test_array_analysis() {
        let config = ConversionConfig::default();
        let formatter = MixedArrayFormatter::new(&config);

        // All primitives
        let array = json!([1, 2, "hello", true]);
        let analysis = formatter.analyze_array(array.as_array().unwrap());
        assert_eq!(analysis.array_type, ArrayType::AllPrimitives);
        assert_eq!(analysis.total_elements, 4);

        // All objects
        let array = json!([{}, {"a": 1}]);
        let analysis = formatter.analyze_array(array.as_array().unwrap());
        assert_eq!(analysis.array_type, ArrayType::AllObjects);

        // Mixed
        let array = json!([1, {}, []]);
        let analysis = formatter.analyze_array(array.as_array().unwrap());
        assert_eq!(analysis.array_type, ArrayType::Mixed);
    }

    #[test]
    fn test_pretty_vs_compact() {
        let config = ConversionConfig {
            pretty: true,
            ..Default::default()
        };
        let mut formatter = MixedArrayFormatter::new(&config);

        let array = json!([1, 2, 3]);
        let pretty_result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();

        let config = ConversionConfig {
            pretty: false,
            ..Default::default()
        };
        let mut formatter = MixedArrayFormatter::new(&config);
        let compact_result = formatter
            .format_mixed_array(array.as_array().unwrap())
            .unwrap();

        assert!(pretty_result.len() >= compact_result.len());
    }
}