1use serde::{Deserialize, Serialize};
10
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
16pub enum Value {
17 Null,
19 Bool(bool),
20 Int(i64),
21 Float(f64),
22 Bytes(#[serde(with = "serde_bytes")] Vec<u8>),
25 Str(String),
26 Array(Vec<Value>),
27 Map(Vec<(Value, Value)>),
28}
29
30impl Value {
31 pub fn as_str(&self) -> Option<&str> {
33 match self {
34 Self::Str(s) => Some(s.as_str()),
35 _ => None,
36 }
37 }
38
39 pub fn as_bytes(&self) -> Option<&[u8]> {
41 match self {
42 Self::Bytes(b) => Some(b.as_slice()),
43 Self::Str(s) => Some(s.as_bytes()),
44 _ => None,
45 }
46 }
47
48 pub fn as_int(&self) -> Option<i64> {
50 match self {
51 Self::Int(i) => Some(*i),
52 _ => None,
53 }
54 }
55
56 pub fn as_float(&self) -> Option<f64> {
58 match self {
59 Self::Float(f) => Some(*f),
60 Self::Int(i) => Some(*i as f64),
61 _ => None,
62 }
63 }
64
65 pub fn as_bool(&self) -> Option<bool> {
67 match self {
68 Self::Bool(b) => Some(*b),
69 _ => None,
70 }
71 }
72
73 pub fn as_array(&self) -> Option<&[Value]> {
75 match self {
76 Self::Array(items) => Some(items.as_slice()),
77 _ => None,
78 }
79 }
80
81 pub fn as_map(&self) -> Option<&[(Value, Value)]> {
83 match self {
84 Self::Map(pairs) => Some(pairs.as_slice()),
85 _ => None,
86 }
87 }
88
89 pub fn map_get(&self, key: &str) -> Option<&Value> {
91 self.as_map()?
92 .iter()
93 .find(|(k, _)| k.as_str() == Some(key))
94 .map(|(_, v)| v)
95 }
96
97 pub fn is_null(&self) -> bool {
99 matches!(self, Self::Null)
100 }
101}
102
103impl From<bool> for Value {
104 fn from(b: bool) -> Self {
105 Self::Bool(b)
106 }
107}
108impl From<i64> for Value {
109 fn from(i: i64) -> Self {
110 Self::Int(i)
111 }
112}
113impl From<f64> for Value {
114 fn from(f: f64) -> Self {
115 Self::Float(f)
116 }
117}
118impl From<String> for Value {
119 fn from(s: String) -> Self {
120 Self::Str(s)
121 }
122}
123impl From<&str> for Value {
124 fn from(s: &str) -> Self {
125 Self::Str(s.to_owned())
126 }
127}
128impl From<Vec<u8>> for Value {
129 fn from(b: Vec<u8>) -> Self {
130 Self::Bytes(b)
131 }
132}
133impl From<Vec<Value>> for Value {
134 fn from(items: Vec<Value>) -> Self {
135 Self::Array(items)
136 }
137}
138
139#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
143pub struct Request {
144 pub id: u32,
145 pub command: String,
146 pub args: Vec<Value>,
147}
148
149#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
153pub struct Response {
154 pub id: u32,
155 pub result: Result<Value, String>,
156}
157
158impl Response {
159 pub fn ok(id: u32, value: Value) -> Self {
161 Self {
162 id,
163 result: Ok(value),
164 }
165 }
166
167 pub fn err(id: u32, message: impl Into<String>) -> Self {
169 Self {
170 id,
171 result: Err(message.into()),
172 }
173 }
174}