1use std::collections::BTreeMap;
2
3use crate::error::{Error, Result};
4
5#[derive(Clone, Debug, PartialEq)]
6#[non_exhaustive]
7pub enum Value {
8 Null,
9 Boolean(bool),
10 Integer(i64),
11 Float(f64),
12 String(String),
13 List(Vec<Value>),
14 Map(BTreeMap<String, Value>),
15 Node(NodeValue),
16 Relationship(RelationshipValue),
17 Path(PathValue),
18}
19
20#[derive(Clone, Debug, PartialEq)]
21pub struct NodeValue {
22 pub record_id: Option<u64>,
24 pub id: String,
25 pub labels: Vec<String>,
26 pub properties: Properties,
27}
28
29#[derive(Clone, Debug, PartialEq)]
30pub struct RelationshipValue {
31 pub record_id: Option<u64>,
33 pub start_record_id: Option<u64>,
35 pub end_record_id: Option<u64>,
37 pub id: String,
38 pub start: String,
39 pub end: String,
40 pub r#type: String,
41 pub properties: Properties,
42}
43
44#[derive(Clone, Debug, PartialEq)]
45pub struct PathValue {
46 pub nodes: Vec<NodeValue>,
47 pub relationships: Vec<RelationshipValue>,
48}
49
50impl NodeValue {
51 pub fn new(id: String, labels: Vec<String>, properties: Properties) -> Self {
52 Self {
53 record_id: None,
54 id,
55 labels,
56 properties,
57 }
58 }
59
60 pub fn stored(record_id: u64, id: String, labels: Vec<String>, properties: Properties) -> Self {
61 Self {
62 record_id: Some(record_id),
63 id,
64 labels,
65 properties,
66 }
67 }
68}
69
70impl RelationshipValue {
71 pub fn new(
72 id: String,
73 start: String,
74 end: String,
75 r#type: String,
76 properties: Properties,
77 ) -> Self {
78 Self {
79 record_id: None,
80 start_record_id: None,
81 end_record_id: None,
82 id,
83 start,
84 end,
85 r#type,
86 properties,
87 }
88 }
89
90 #[allow(clippy::too_many_arguments)]
91 pub fn stored(
92 record_id: u64,
93 start_record_id: u64,
94 end_record_id: u64,
95 id: String,
96 start: String,
97 end: String,
98 r#type: String,
99 properties: Properties,
100 ) -> Self {
101 Self {
102 record_id: Some(record_id),
103 start_record_id: Some(start_record_id),
104 end_record_id: Some(end_record_id),
105 id,
106 start,
107 end,
108 r#type,
109 properties,
110 }
111 }
112}
113
114impl Value {
115 pub fn from_json(value: serde_json::Value) -> Result<Self> {
116 match value {
117 serde_json::Value::Null => Ok(Value::Null),
118 serde_json::Value::Bool(value) => Ok(Value::Boolean(value)),
119 serde_json::Value::Number(value) => number_from_json(value),
120 serde_json::Value::String(value) => Ok(Value::String(value)),
121 serde_json::Value::Array(values) => values
122 .into_iter()
123 .map(Value::from_json)
124 .collect::<Result<Vec<_>>>()
125 .map(Value::List),
126 serde_json::Value::Object(values) => values
127 .into_iter()
128 .map(|(key, value)| Value::from_json(value).map(|value| (key, value)))
129 .collect::<Result<BTreeMap<_, _>>>()
130 .map(Value::Map),
131 }
132 }
133}
134
135fn number_from_json(value: serde_json::Number) -> Result<Value> {
136 if let Some(integer) = value.as_i64() {
137 return Ok(Value::Integer(integer));
138 }
139
140 let raw = value.to_string();
141 if value.as_u64().is_some() || !raw.contains(['.', 'e', 'E']) {
142 return Err(Error::DataLoad(format!("unsupported JSON number {value}")));
143 }
144
145 value
146 .as_f64()
147 .map(Value::Float)
148 .ok_or_else(|| Error::DataLoad(format!("unsupported JSON number {value}")))
149}
150
151pub type Properties = BTreeMap<String, Value>;
152
153const BTREE_ENTRY_OVERHEAD: usize = 3 * std::mem::size_of::<usize>();
154
155pub(crate) fn estimated_properties_heap_bytes(properties: &Properties) -> Option<usize> {
156 let mut bytes = 0_usize;
157 for (key, value) in properties {
158 bytes = bytes
159 .checked_add(std::mem::size_of::<String>())?
160 .checked_add(std::mem::size_of::<Value>())?
161 .checked_add(BTREE_ENTRY_OVERHEAD)?
162 .checked_add(key.len())?
163 .checked_add(value.estimated_heap_bytes()?)?;
164 }
165 Some(bytes)
166}
167
168impl Value {
169 pub(crate) fn estimated_heap_bytes(&self) -> Option<usize> {
170 match self {
171 Self::Null | Self::Boolean(_) | Self::Integer(_) | Self::Float(_) => Some(0),
172 Self::String(value) => Some(value.len()),
173 Self::List(values) => {
174 let mut bytes = values.len().checked_mul(std::mem::size_of::<Value>())?;
175 for value in values {
176 bytes = bytes.checked_add(value.estimated_heap_bytes()?)?;
177 }
178 Some(bytes)
179 }
180 Self::Map(values) => estimated_properties_heap_bytes(values),
181 Self::Node(node) => estimated_node_value_heap_bytes(node),
182 Self::Relationship(relationship) => {
183 estimated_relationship_value_heap_bytes(relationship)
184 }
185 Self::Path(path) => {
186 let mut bytes = path
187 .nodes
188 .len()
189 .checked_mul(std::mem::size_of::<NodeValue>())?
190 .checked_add(
191 path.relationships
192 .len()
193 .checked_mul(std::mem::size_of::<RelationshipValue>())?,
194 )?;
195 for node in &path.nodes {
196 bytes = bytes.checked_add(estimated_node_value_heap_bytes(node)?)?;
197 }
198 for relationship in &path.relationships {
199 bytes = bytes
200 .checked_add(estimated_relationship_value_heap_bytes(relationship)?)?;
201 }
202 Some(bytes)
203 }
204 }
205 }
206}
207
208fn estimated_node_value_heap_bytes(node: &NodeValue) -> Option<usize> {
209 let mut bytes = node.id.len().checked_add(
210 node.labels
211 .len()
212 .checked_mul(std::mem::size_of::<String>())?,
213 )?;
214 for label in &node.labels {
215 bytes = bytes.checked_add(label.len())?;
216 }
217 bytes.checked_add(estimated_properties_heap_bytes(&node.properties)?)
218}
219
220fn estimated_relationship_value_heap_bytes(relationship: &RelationshipValue) -> Option<usize> {
221 relationship
222 .id
223 .len()
224 .checked_add(relationship.start.len())?
225 .checked_add(relationship.end.len())?
226 .checked_add(relationship.r#type.len())?
227 .checked_add(estimated_properties_heap_bytes(&relationship.properties)?)
228}
229
230#[cfg(test)]
231mod tests {
232 use super::Value;
233
234 #[test]
235 fn converts_json_scalars_and_collections() {
236 let json = serde_json::json!({
237 "none": null,
238 "active": true,
239 "age": 42,
240 "score": 9.5,
241 "name": "Alice",
242 "tags": ["a", "b"],
243 "nested": {"x": 1}
244 });
245
246 let value = Value::from_json(json).expect("convert JSON value");
247
248 match value {
249 Value::Map(map) => {
250 assert_eq!(map["none"], Value::Null);
251 assert_eq!(map["active"], Value::Boolean(true));
252 assert_eq!(map["age"], Value::Integer(42));
253 assert_eq!(map["score"], Value::Float(9.5));
254 assert_eq!(map["name"], Value::String("Alice".to_string()));
255 assert_eq!(
256 map["tags"],
257 Value::List(vec![
258 Value::String("a".to_string()),
259 Value::String("b".to_string())
260 ])
261 );
262 }
263 other => panic!("expected map, got {other:?}"),
264 }
265 }
266
267 #[test]
268 fn rejects_unsigned_integers_outside_i64_range() {
269 let json = serde_json::json!(9223372036854775808u64);
270
271 let error = Value::from_json(json).expect_err("out of range unsigned integer");
272
273 assert!(error.to_string().contains("unsupported JSON number"));
274 }
275
276 #[test]
277 fn rejects_integer_literals_larger_than_u64_range() {
278 let json: serde_json::Value =
279 serde_json::from_str("18446744073709551616").expect("parse JSON number");
280
281 let error = Value::from_json(json).expect_err("out of range integer literal");
282
283 assert!(error.to_string().contains("unsupported JSON number"));
284 }
285}