Skip to main content

agent_tui_common/common/
rpc_id.rs

1//! JSON-RPC request identifier shared by transports and protocol adapters.
2
3use std::fmt;
4
5use serde::Deserialize;
6use serde::Serialize;
7
8#[derive(
9    Debug,
10    Clone,
11    PartialEq,
12    Eq,
13    PartialOrd,
14    Ord,
15    Hash,
16    Deserialize,
17    Serialize
18)]
19#[serde(untagged)]
20pub enum RpcId {
21    String(String),
22    Integer(i64),
23}
24
25impl RpcId {
26    pub fn integer(value: u64) -> Self {
27        i64::try_from(value).map_or_else(|_| Self::String(value.to_string()), Self::Integer)
28    }
29}
30
31impl From<u64> for RpcId {
32    fn from(value: u64) -> Self {
33        Self::integer(value)
34    }
35}
36
37impl From<u32> for RpcId {
38    fn from(value: u32) -> Self {
39        Self::Integer(i64::from(value))
40    }
41}
42
43impl From<i64> for RpcId {
44    fn from(value: i64) -> Self {
45        Self::Integer(value)
46    }
47}
48
49impl From<i32> for RpcId {
50    fn from(value: i32) -> Self {
51        Self::Integer(i64::from(value))
52    }
53}
54
55impl From<String> for RpcId {
56    fn from(value: String) -> Self {
57        Self::String(value)
58    }
59}
60
61impl From<&str> for RpcId {
62    fn from(value: &str) -> Self {
63        Self::String(value.to_string())
64    }
65}
66
67impl From<&RpcId> for RpcId {
68    fn from(value: &RpcId) -> Self {
69        value.clone()
70    }
71}
72
73impl fmt::Display for RpcId {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self {
76            Self::String(value) => f.write_str(value),
77            Self::Integer(value) => write!(f, "{value}"),
78        }
79    }
80}