1use serde_json::Value;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum TopLevel {
11 Object,
13 Array,
15 Scalar,
17}
18
19#[derive(Debug, Clone)]
24pub struct JsonShape {
25 pub top_level: TopLevel,
27 pub item_count: usize,
29 pub is_uniform_array: bool,
31 pub max_depth: usize,
33 pub char_count: usize,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ToonStrategy {
40 Toon,
42 Json,
44}
45
46#[derive(Debug, Clone)]
48pub struct ToonError {
49 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#[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
115fn 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#[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
153pub 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 #[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 #[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 #[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}