Skip to main content

agent_tui_adapters/adapters/
rpc_value.rs

1//! RPC value wrappers and helpers.
2
3use serde::Serialize;
4use serde_json::Value;
5use tracing::debug;
6
7use crate::adapters::ValueExt;
8
9#[derive(Clone, Debug)]
10pub struct RpcValue(Value);
11
12#[derive(Clone, Copy, Debug)]
13pub struct RpcValueRef<'a>(&'a Value);
14
15#[derive(Clone, Copy, Debug)]
16pub struct RpcArrayRef<'a>(&'a [Value]);
17
18impl RpcValue {
19    pub fn new(value: Value) -> Self {
20        Self(value)
21    }
22
23    pub fn as_ref(&self) -> RpcValueRef<'_> {
24        RpcValueRef(&self.0)
25    }
26
27    pub fn get(&self, key: &str) -> Option<RpcValueRef<'_>> {
28        self.0.get(key).map(RpcValueRef)
29    }
30
31    pub fn str_or<'a>(&'a self, key: &str, default: &'a str) -> &'a str {
32        self.0.str_or(key, default)
33    }
34
35    pub fn u64_or(&self, key: &str, default: u64) -> u64 {
36        self.0.u64_or(key, default)
37    }
38
39    pub fn bool_or(&self, key: &str, default: bool) -> bool {
40        self.0.bool_or(key, default)
41    }
42
43    pub fn to_pretty_json(&self) -> String {
44        serde_json::to_string_pretty(&self.0).unwrap_or_else(|err| {
45            debug!(error = %err, "Failed to serialize RPC value to JSON");
46            String::new()
47        })
48    }
49}
50
51impl Serialize for RpcValue {
52    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
53    where
54        S: serde::Serializer,
55    {
56        self.0.serialize(serializer)
57    }
58}
59
60impl Serialize for RpcValueRef<'_> {
61    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62    where
63        S: serde::Serializer,
64    {
65        self.0.serialize(serializer)
66    }
67}
68
69impl<'a> RpcValueRef<'a> {
70    pub fn get(&self, key: &str) -> Option<RpcValueRef<'a>> {
71        self.0.get(key).map(RpcValueRef)
72    }
73
74    pub fn as_str(&self) -> Option<&'a str> {
75        self.0.as_str()
76    }
77
78    pub fn as_u64(&self) -> Option<u64> {
79        self.0.as_u64()
80    }
81
82    pub fn as_bool(&self) -> Option<bool> {
83        self.0.as_bool()
84    }
85
86    pub fn as_array(&self) -> Option<RpcArrayRef<'a>> {
87        self.0.as_array().map(|arr| RpcArrayRef(arr))
88    }
89
90    pub fn str_or(&self, key: &str, default: &'a str) -> &'a str {
91        self.0.str_or(key, default)
92    }
93
94    pub fn u64_or(&self, key: &str, default: u64) -> u64 {
95        self.0.u64_or(key, default)
96    }
97
98    pub fn bool_or(&self, key: &str, default: bool) -> bool {
99        self.0.bool_or(key, default)
100    }
101}
102
103impl<'a> RpcArrayRef<'a> {
104    pub fn iter(self) -> impl Iterator<Item = RpcValueRef<'a>> {
105        self.0.iter().map(RpcValueRef)
106    }
107
108    pub fn is_empty(&self) -> bool {
109        self.0.is_empty()
110    }
111}