adk_code/embedded_python/
convert.rs1use monty_types::{DictPairs, MontyObject};
17use serde_json::{Map, Number, Value};
18
19const MAX_CONVERSION_DEPTH: usize = 64;
23
24const DEPTH_PLACEHOLDER: &str = "<truncated: nesting depth limit reached>";
26
27pub fn json_to_monty(value: Value) -> MontyObject {
44 to_monty(value, MAX_CONVERSION_DEPTH)
45}
46
47fn to_monty(value: Value, budget: usize) -> MontyObject {
48 if budget == 0 {
49 return MontyObject::String(DEPTH_PLACEHOLDER.to_string());
50 }
51 match value {
52 Value::Null => MontyObject::None,
53 Value::Bool(b) => MontyObject::Bool(b),
54 Value::Number(n) => {
55 if let Some(i) = n.as_i64() {
56 MontyObject::Int(i)
57 } else {
58 match n.as_f64() {
59 Some(f) => MontyObject::Float(f),
63 None => MontyObject::String(n.to_string()),
67 }
68 }
69 }
70 Value::String(s) => MontyObject::String(s),
71 Value::Array(items) => {
72 MontyObject::List(items.into_iter().map(|v| to_monty(v, budget - 1)).collect())
73 }
74 Value::Object(map) => {
75 let pairs: Vec<(MontyObject, MontyObject)> = map
76 .into_iter()
77 .map(|(k, v)| (MontyObject::String(k), to_monty(v, budget - 1)))
78 .collect();
79 MontyObject::Dict(DictPairs::from(pairs))
80 }
81 }
82}
83
84pub fn monty_to_json(obj: &MontyObject) -> Value {
104 to_json(obj, MAX_CONVERSION_DEPTH)
105}
106
107fn to_json(obj: &MontyObject, budget: usize) -> Value {
108 if budget == 0 {
109 return Value::String(DEPTH_PLACEHOLDER.to_string());
110 }
111 match obj {
112 MontyObject::None => Value::Null,
113 MontyObject::Bool(b) => Value::Bool(*b),
114 MontyObject::Int(i) => Value::Number(Number::from(*i)),
115 MontyObject::Float(f) => Number::from_f64(*f).map_or(Value::Null, Value::Number),
117 MontyObject::String(s) => Value::String(s.clone()),
118 MontyObject::Path(p) => Value::String(p.clone()),
119 MontyObject::List(items)
121 | MontyObject::Tuple(items)
122 | MontyObject::Set(items)
123 | MontyObject::FrozenSet(items) => {
124 Value::Array(items.iter().map(|item| to_json(item, budget - 1)).collect())
125 }
126 MontyObject::Dict(pairs) => dict_to_json(pairs, budget),
127 other => Value::String(guarded_repr(other, budget)),
132 }
133}
134
135fn dict_to_json(pairs: &DictPairs, budget: usize) -> Value {
141 let mut map = Map::new();
142 for (key, value) in pairs {
143 map.insert(key_string(key, budget), to_json(value, budget - 1));
144 }
145 Value::Object(map)
146}
147
148pub(crate) fn monty_key_string(key: &MontyObject) -> String {
151 key_string(key, MAX_CONVERSION_DEPTH)
152}
153
154fn key_string(key: &MontyObject, budget: usize) -> String {
155 match key {
156 MontyObject::String(s) => s.clone(),
157 other => guarded_repr(other, budget),
158 }
159}
160
161fn guarded_repr(obj: &MontyObject, budget: usize) -> String {
165 if exceeds_depth(obj, budget) { DEPTH_PLACEHOLDER.to_string() } else { obj.py_repr() }
166}
167
168fn exceeds_depth(obj: &MontyObject, budget: usize) -> bool {
171 if budget == 0 {
172 return true;
173 }
174 match obj {
175 MontyObject::List(items)
176 | MontyObject::Tuple(items)
177 | MontyObject::Set(items)
178 | MontyObject::FrozenSet(items)
179 | MontyObject::NamedTuple { values: items, .. } => {
180 items.iter().any(|item| exceeds_depth(item, budget - 1))
181 }
182 MontyObject::Dict(pairs) => pairs
183 .into_iter()
184 .any(|(k, v)| exceeds_depth(k, budget - 1) || exceeds_depth(v, budget - 1)),
185 _ => false,
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use serde_json::json;
194
195 #[test]
196 fn round_trips_json_native_values() {
197 let cases = [
198 json!(null),
199 json!(true),
200 json!(42),
201 json!(3.5),
202 json!("hello"),
203 json!([1, 2, 3]),
204 json!({"nested": {"n": 7}, "list": [1, "two"]}),
205 ];
206 for case in cases {
207 let monty = json_to_monty(case.clone());
208 assert_eq!(monty_to_json(&monty), case);
209 }
210 }
211
212 #[test]
213 fn large_u64_degrades_to_float() {
214 let big = json!(u64::MAX);
215 assert!(matches!(json_to_monty(big), MontyObject::Float(_)));
216 }
217
218 #[test]
219 fn non_json_native_value_degrades_to_repr() {
220 let tuple = MontyObject::Tuple(vec![MontyObject::Int(1), MontyObject::Int(2)]);
221 assert_eq!(monty_to_json(&tuple), json!([1, 2]));
222 let bytes = MontyObject::Bytes(vec![1, 2]);
223 assert!(monty_to_json(&bytes).is_string());
224 }
225
226 #[test]
227 fn nan_and_infinity_degrade_to_null() {
228 for f in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
229 assert_eq!(monty_to_json(&MontyObject::Float(f)), Value::Null);
230 }
231 }
232
233 #[test]
234 fn path_projects_to_string() {
235 let path = MontyObject::Path("/data/report.csv".to_string());
236 assert_eq!(monty_to_json(&path), json!("/data/report.csv"));
237 }
238
239 #[test]
240 fn colliding_dict_keys_last_one_wins() {
241 let pairs = DictPairs::from(vec![
242 (MontyObject::Int(1), MontyObject::String("int".to_string())),
243 (MontyObject::String("1".to_string()), MontyObject::String("str".to_string())),
244 ]);
245 assert_eq!(monty_to_json(&MontyObject::Dict(pairs)), json!({"1": "str"}));
246 }
247
248 #[test]
249 fn deep_monty_nesting_degrades_instead_of_overflowing() {
250 let mut obj = MontyObject::Int(1);
253 for _ in 0..2_000 {
254 obj = MontyObject::List(vec![obj]);
255 }
256 let json = monty_to_json(&obj);
257 assert!(json.is_array());
258 assert!(json.to_string().contains(DEPTH_PLACEHOLDER));
259 }
260
261 #[test]
262 fn deep_json_nesting_degrades_instead_of_overflowing() {
263 let mut value = json!(1);
266 for _ in 0..2_000 {
267 value = Value::Array(vec![value]);
268 }
269 let monty = json_to_monty(value);
270 assert!(matches!(monty, MontyObject::List(_)));
271 }
272
273 #[test]
274 fn deep_tuple_dict_key_degrades_instead_of_overflowing() {
275 let mut key = MontyObject::Tuple(vec![MontyObject::Int(1)]);
276 for _ in 0..2_000 {
277 key = MontyObject::Tuple(vec![key]);
278 }
279 let pairs = DictPairs::from(vec![(key, MontyObject::Int(1))]);
280 let json = monty_to_json(&MontyObject::Dict(pairs));
281 assert_eq!(json, json!({DEPTH_PLACEHOLDER: 1}));
282 }
283
284 #[test]
285 fn shallow_values_are_unaffected_by_the_depth_cap() {
286 let value = json!({"a": [{"b": [{"c": 1}]}]});
287 assert_eq!(monty_to_json(&json_to_monty(value.clone())), value);
288 }
289}