Skip to main content

gitflow_core/
toon.rs

1//! TOON (Token-Oriented Object Notation) output support.
2//!
3//! Provides structure analysis, strategy selection, and TOON encoding
4//! for token-efficient output. Uses the `toon-format` crate for encoding.
5
6use serde_json::Value;
7
8/// The top-level type of a JSON value.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum TopLevel {
11    /// A JSON object (`{...}`).
12    Object,
13    /// A JSON array (`[...]`).
14    Array,
15    /// A JSON scalar (string, number, bool, null).
16    Scalar,
17}
18
19/// Structural characteristics of a JSON value.
20///
21/// Produced by [`analyze`] and consumed by [`select_strategy`] to decide
22/// whether TOON or JSON encoding is more token-efficient.
23#[derive(Debug, Clone)]
24pub struct JsonShape {
25    /// The top-level JSON type.
26    pub top_level: TopLevel,
27    /// Number of items if top-level is an array, 0 otherwise.
28    pub item_count: usize,
29    /// `true` if top-level is an array and all items are objects with identical key sets.
30    pub is_uniform_array: bool,
31    /// Maximum nesting depth (0 for flat values).
32    pub max_depth: usize,
33    /// Total character count of the pretty-printed JSON representation.
34    pub char_count: usize,
35}
36
37/// Strategy selected by [`select_strategy`] for encoding output.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ToonStrategy {
40    /// Encode as TOON (uniform arrays or deeply nested structures).
41    Toon,
42    /// Keep as JSON (small data or structures not suited for TOON).
43    Json,
44}
45
46/// Error type for TOON encoding failures.
47#[derive(Debug, Clone)]
48pub struct ToonError {
49    /// Human-readable error message.
50    pub message: String,
51}
52
53impl std::fmt::Display for ToonError {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "TOON encoding error: {}", self.message)
56    }
57}
58
59impl std::error::Error for ToonError {}
60
61/// Analyze the structure of a JSON value.
62///
63/// Performs a single-pass O(n) traversal to collect structural metrics
64/// used by [`select_strategy`].
65#[must_use]
66pub fn analyze(value: &Value) -> JsonShape {
67    let char_count = serde_json::to_string_pretty(value).map_or(0, |s| s.len());
68
69    let top_level = match value {
70        Value::Object(_) => TopLevel::Object,
71        Value::Array(_) => TopLevel::Array,
72        _ => TopLevel::Scalar,
73    };
74
75    let (item_count, is_uniform_array) = match value {
76        Value::Array(arr) => {
77            let count = arr.len();
78            let uniform = count > 0
79                && arr.iter().all(|item| {
80                    item.as_object().is_some_and(|obj| {
81                        let keys: Vec<&String> = {
82                            let mut ks: Vec<_> = obj.keys().collect();
83                            ks.sort_unstable();
84                            ks
85                        };
86                        arr.first().is_some_and(|first| {
87                            let first_keys: Vec<_> = first
88                                .as_object()
89                                .map(|o| {
90                                    let mut ks: Vec<_> = o.keys().collect();
91                                    ks.sort_unstable();
92                                    ks
93                                })
94                                .unwrap_or_default();
95                            keys == first_keys
96                        })
97                    })
98                });
99            (count, uniform)
100        }
101        _ => (0, false),
102    };
103
104    let max_depth = compute_depth(value, 0);
105
106    JsonShape {
107        top_level,
108        item_count,
109        is_uniform_array,
110        max_depth,
111        char_count,
112    }
113}
114
115/// Recursively compute the maximum nesting depth.
116fn compute_depth(value: &Value, current: usize) -> usize {
117    match value {
118        Value::Object(obj) => obj
119            .values()
120            .map(|v| compute_depth(v, current + 1))
121            .max()
122            .unwrap_or(current),
123        Value::Array(arr) => arr
124            .iter()
125            .map(|v| compute_depth(v, current + 1))
126            .max()
127            .unwrap_or(current),
128        _ => current,
129    }
130}
131
132/// Select the optimal encoding strategy based on structural analysis.
133///
134/// Rules (applied in order):
135/// 1. `char_count < 200` → [`ToonStrategy::Json`] (not worth converting)
136/// 2. Uniform array with `item_count >= 5` → [`ToonStrategy::Toon`]
137/// 3. `max_depth > 3` → [`ToonStrategy::Toon`]
138/// 4. Otherwise → [`ToonStrategy::Json`]
139#[must_use]
140pub fn select_strategy(shape: &JsonShape) -> ToonStrategy {
141    if shape.char_count < 200 {
142        return ToonStrategy::Json;
143    }
144    if shape.top_level == TopLevel::Array && shape.is_uniform_array && shape.item_count >= 5 {
145        return ToonStrategy::Toon;
146    }
147    if shape.max_depth > 3 {
148        return ToonStrategy::Toon;
149    }
150    ToonStrategy::Json
151}
152
153/// Encode a JSON value as TOON format.
154///
155/// # Errors
156///
157/// Returns [`ToonError`] if the `toon-format` crate fails to encode.
158pub fn encode(value: &Value) -> Result<String, ToonError> {
159    toon_format::encode_default(value).map_err(|e| ToonError {
160        message: e.to_string(),
161    })
162}
163
164#[cfg(test)]
165#[allow(
166    clippy::expect_used,
167    clippy::unwrap_used,
168    reason = "Tests legitimately unwrap known-good fixture data"
169)]
170mod tests {
171    use serde_json::json;
172
173    use super::*;
174
175    // ── analyze tests ──────────────────────────────────────────────
176
177    #[test]
178    fn test_analyze_uniform_array() {
179        let value = json!([
180            {"id": 1, "name": "a"},
181            {"id": 2, "name": "b"},
182            {"id": 3, "name": "c"},
183            {"id": 4, "name": "d"},
184            {"id": 5, "name": "e"}
185        ]);
186        let shape = analyze(&value);
187        assert_eq!(shape.top_level, TopLevel::Array);
188        assert_eq!(shape.item_count, 5);
189        assert!(shape.is_uniform_array);
190    }
191
192    #[test]
193    fn test_analyze_mixed_array() {
194        let value = json!([
195            {"a": 1, "b": 2},
196            {"a": 3, "c": 4}
197        ]);
198        let shape = analyze(&value);
199        assert_eq!(shape.top_level, TopLevel::Array);
200        assert_eq!(shape.item_count, 2);
201        assert!(!shape.is_uniform_array);
202    }
203
204    #[test]
205    fn test_analyze_deep_nesting() {
206        let value = json!({"a": {"b": {"c": {"d": {"e": 1}}}}});
207        let shape = analyze(&value);
208        assert_eq!(shape.top_level, TopLevel::Object);
209        assert_eq!(shape.max_depth, 5);
210    }
211
212    #[test]
213    fn test_analyze_small_data() {
214        let value = json!({"x": 1});
215        let shape = analyze(&value);
216        assert!(shape.char_count < 200);
217    }
218
219    #[test]
220    fn test_analyze_scalar() {
221        let value = json!(42);
222        let shape = analyze(&value);
223        assert_eq!(shape.top_level, TopLevel::Scalar);
224        assert_eq!(shape.item_count, 0);
225        assert!(!shape.is_uniform_array);
226    }
227
228    // ── select_strategy tests ──────────────────────────────────────
229
230    #[test]
231    fn test_strategy_small_data_returns_json() {
232        let shape = JsonShape {
233            top_level: TopLevel::Array,
234            item_count: 10,
235            is_uniform_array: true,
236            max_depth: 1,
237            char_count: 100,
238        };
239        assert_eq!(select_strategy(&shape), ToonStrategy::Json);
240    }
241
242    #[test]
243    fn test_strategy_uniform_array_returns_toon() {
244        let shape = JsonShape {
245            top_level: TopLevel::Array,
246            item_count: 10,
247            is_uniform_array: true,
248            max_depth: 1,
249            char_count: 500,
250        };
251        assert_eq!(select_strategy(&shape), ToonStrategy::Toon);
252    }
253
254    #[test]
255    fn test_strategy_deep_nesting_returns_toon() {
256        let shape = JsonShape {
257            top_level: TopLevel::Object,
258            item_count: 0,
259            is_uniform_array: false,
260            max_depth: 5,
261            char_count: 500,
262        };
263        assert_eq!(select_strategy(&shape), ToonStrategy::Toon);
264    }
265
266    #[test]
267    fn test_strategy_default_returns_json() {
268        let shape = JsonShape {
269            top_level: TopLevel::Object,
270            item_count: 0,
271            is_uniform_array: false,
272            max_depth: 2,
273            char_count: 500,
274        };
275        assert_eq!(select_strategy(&shape), ToonStrategy::Json);
276    }
277
278    // ── encode tests ───────────────────────────────────────────────
279
280    #[test]
281    fn test_toon_encode_simple_object() {
282        let value = json!({"name": "Alice", "age": 30});
283        let result = encode(&value);
284        assert!(result.is_ok());
285        let encoded = result.unwrap();
286        assert!(encoded.contains("name"));
287        assert!(encoded.contains("Alice"));
288    }
289
290    #[test]
291    fn test_toon_encode_array() {
292        let value = json!([
293            {"id": 1, "name": "a"},
294            {"id": 2, "name": "b"},
295            {"id": 3, "name": "c"},
296            {"id": 4, "name": "d"},
297            {"id": 5, "name": "e"}
298        ]);
299        let result = encode(&value);
300        assert!(result.is_ok());
301    }
302}