Skip to main content

codetether_agent/tool/tetherscript/convert/
to_json.rs

1use std::collections::HashMap;
2
3use serde_json::{Map, Number, Value};
4use tetherscript::value::{ResultValue, Value as TetherScriptValue};
5
6pub fn tetherscript_to_json(value: &TetherScriptValue) -> Value {
7    match value {
8        TetherScriptValue::Nil => Value::Null,
9        TetherScriptValue::Int(value) => Value::Number(Number::from(*value)),
10        TetherScriptValue::Float(value) => {
11            Number::from_f64(*value).map_or(Value::Null, Value::Number)
12        }
13        TetherScriptValue::Bool(value) => Value::Bool(*value),
14        TetherScriptValue::Str(value) => Value::String((**value).clone()),
15        TetherScriptValue::List(values) => {
16            Value::Array(values.borrow().iter().map(tetherscript_to_json).collect())
17        }
18        TetherScriptValue::Map(values) => Value::Object(map_to_json(&values.borrow())),
19        TetherScriptValue::Result(result) => result_to_json(result),
20        TetherScriptValue::Bytes(bytes) => Value::Array(
21            bytes
22                .borrow()
23                .iter()
24                .map(|byte| Value::Number(Number::from(*byte)))
25                .collect(),
26        ),
27        TetherScriptValue::Fn(_)
28        | TetherScriptValue::VmFn(_)
29        | TetherScriptValue::Native(_)
30        | TetherScriptValue::Capability(_) => Value::String(value.to_string()),
31    }
32}
33
34fn map_to_json(values: &HashMap<String, TetherScriptValue>) -> Map<String, Value> {
35    values
36        .iter()
37        .map(|(key, value)| (key.clone(), tetherscript_to_json(value)))
38        .collect()
39}
40
41fn result_to_json(result: &ResultValue) -> Value {
42    match result {
43        ResultValue::Ok(value) => serde_json::json!({ "ok": tetherscript_to_json(value) }),
44        ResultValue::Err(message) => serde_json::json!({ "err": message }),
45    }
46}