1use crate::json::{from_slice as json_from_slice, Map, Value as JsonValue};
2use crate::Value;
3
4const MAX_JSON_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
5
6impl Value {
7 pub fn to_json(&self) -> JsonValue {
12 match self {
13 Value::Null => JsonValue::Null,
14 Value::Integer(value) => exact_i64_to_json(*value),
15 Value::UnsignedInteger(value) => exact_u64_to_json(*value),
16 Value::Float(value) => JsonValue::Number(*value),
17 Value::Text(value) => JsonValue::String(value.to_string()),
18 Value::Blob(value) => JsonValue::String(hex_encode(value)),
19 Value::Boolean(value) => JsonValue::Bool(*value),
20 Value::Timestamp(value) => exact_i64_to_json(*value),
21 Value::Duration(value) => exact_i64_to_json(*value),
22 Value::IpAddr(value) => JsonValue::String(value.to_string()),
23 Value::MacAddr(value) => JsonValue::String(format_mac(value)),
24 Value::Vector(value) => JsonValue::Array(
25 value
26 .iter()
27 .map(|entry| JsonValue::Number(f64::from(*entry)))
28 .collect(),
29 ),
30 Value::Json(value) => json_bytes_to_json(value),
31 Value::Uuid(value) => JsonValue::String(hex_encode(value)),
32 Value::NodeRef(value) | Value::EdgeRef(value) => JsonValue::String(value.clone()),
33 Value::VectorRef(collection, id) => JsonValue::Object(
34 [
35 (
36 "collection".to_string(),
37 JsonValue::String(collection.clone()),
38 ),
39 ("id".to_string(), exact_u64_to_json(*id)),
40 ]
41 .into_iter()
42 .collect(),
43 ),
44 Value::RowRef(table, row_id) => JsonValue::Object(
45 [
46 ("table".to_string(), JsonValue::String(table.clone())),
47 ("row_id".to_string(), exact_u64_to_json(*row_id)),
48 ]
49 .into_iter()
50 .collect(),
51 ),
52 Value::Color([r, g, b]) => JsonValue::String(format!("#{r:02X}{g:02X}{b:02X}")),
53 Value::Email(value) | Value::Url(value) => JsonValue::String(value.clone()),
54 Value::Phone(value) => exact_u64_to_json(*value),
55 Value::Semver(packed) => JsonValue::String(format!(
56 "{}.{}.{}",
57 packed / 1_000_000,
58 (packed / 1_000) % 1_000,
59 packed % 1_000
60 )),
61 Value::Cidr(ip, prefix) => JsonValue::String(format!(
62 "{}.{}.{}.{}/{}",
63 (ip >> 24) & 0xFF,
64 (ip >> 16) & 0xFF,
65 (ip >> 8) & 0xFF,
66 ip & 0xFF,
67 prefix
68 )),
69 Value::Date(days) => JsonValue::Integer(i64::from(*days)),
70 Value::Time(milliseconds) => JsonValue::Integer(i64::from(*milliseconds)),
71 Value::Decimal(_) => exact_decimal_to_json(self.display_string()),
72 Value::DecimalText(value) => exact_decimal_to_json(value.clone()),
73 Value::EnumValue(value) => JsonValue::Integer(i64::from(*value)),
74 Value::Array(values) => JsonValue::Array(values.iter().map(Value::to_json).collect()),
75 Value::TimestampMs(value) => exact_i64_to_json(*value),
76 Value::Ipv4(ip) => JsonValue::String(format_ipv4(*ip)),
77 Value::Ipv6(bytes) => JsonValue::String(std::net::Ipv6Addr::from(*bytes).to_string()),
78 Value::Subnet(ip, mask) => {
79 JsonValue::String(format!("{}/{}", format_ipv4(*ip), mask.leading_ones()))
80 }
81 Value::Port(value) => JsonValue::Integer(i64::from(*value)),
82 Value::Latitude(microdegrees) | Value::Longitude(microdegrees) => {
83 JsonValue::Number(f64::from(*microdegrees) / 1_000_000.0)
84 }
85 Value::GeoPoint(latitude, longitude) => JsonValue::String(format!(
86 "{:.6},{:.6}",
87 f64::from(*latitude) / 1_000_000.0,
88 f64::from(*longitude) / 1_000_000.0
89 )),
90 Value::Country2(code) | Value::Lang2(code) => {
91 JsonValue::String(String::from_utf8_lossy(code).to_string())
92 }
93 Value::Country3(code) | Value::Currency(code) => {
94 JsonValue::String(String::from_utf8_lossy(code).to_string())
95 }
96 Value::Lang5(code) => JsonValue::String(String::from_utf8_lossy(code).to_string()),
97 Value::AssetCode(code) => JsonValue::String(code.clone()),
98 Value::Cron(value) => JsonValue::String(value.to_string()),
99 Value::Temperature(value) => JsonValue::Object(
100 [
101 (
102 "unit".to_string(),
103 JsonValue::String(value.unit().as_str().into()),
104 ),
105 (
106 "minor_units".to_string(),
107 exact_i64_to_json(value.minor_units()),
108 ),
109 (
110 "scale".to_string(),
111 exact_i64_to_json(i64::from(value.scale())),
112 ),
113 ]
114 .into_iter()
115 .collect(),
116 ),
117 Value::Money {
118 asset_code,
119 minor_units,
120 scale,
121 } => JsonValue::Object(
122 [
123 (
124 "asset_code".to_string(),
125 JsonValue::String(asset_code.clone()),
126 ),
127 ("minor_units".to_string(), exact_i64_to_json(*minor_units)),
128 ("scale".to_string(), exact_i64_to_json(i64::from(*scale))),
129 ]
130 .into_iter()
131 .collect(),
132 ),
133 Value::ColorAlpha([r, g, b, a]) => {
134 JsonValue::String(format!("#{r:02X}{g:02X}{b:02X}{a:02X}"))
135 }
136 Value::BigInt(value) => exact_i64_to_json(*value),
137 Value::KeyRef(collection, key) => JsonValue::Object(
138 [
139 (
140 "collection".to_string(),
141 JsonValue::String(collection.clone()),
142 ),
143 ("key".to_string(), JsonValue::String(key.clone())),
144 ]
145 .into_iter()
146 .collect(),
147 ),
148 Value::DocRef(collection, id) => JsonValue::Object(
149 [
150 (
151 "collection".to_string(),
152 JsonValue::String(collection.clone()),
153 ),
154 ("id".to_string(), exact_u64_to_json(*id)),
155 ]
156 .into_iter()
157 .collect(),
158 ),
159 Value::TableRef(name) => JsonValue::String(name.clone()),
160 Value::PageRef(page_id) => exact_u64_to_json(u64::from(*page_id)),
161 Value::Secret(_) | Value::Password(_) => JsonValue::String("***".to_string()),
162 }
163 }
164}
165
166fn exact_i64_to_json(value: i64) -> JsonValue {
167 if (-MAX_JSON_SAFE_INTEGER..=MAX_JSON_SAFE_INTEGER).contains(&value) {
168 JsonValue::Integer(value)
169 } else {
170 single_key_object("$int", JsonValue::String(value.to_string()))
171 }
172}
173
174fn exact_u64_to_json(value: u64) -> JsonValue {
175 if value <= MAX_JSON_SAFE_INTEGER as u64 {
176 JsonValue::Integer(value as i64)
177 } else {
178 single_key_object("$uint", JsonValue::String(value.to_string()))
179 }
180}
181
182fn exact_decimal_to_json(value: String) -> JsonValue {
183 single_key_object("$decimal", JsonValue::String(value))
184}
185
186fn single_key_object(key: &str, value: JsonValue) -> JsonValue {
187 JsonValue::Object([(key.to_string(), value)].into_iter().collect())
188}
189
190pub fn json_bytes_to_json(bytes: &[u8]) -> JsonValue {
193 if bytes.starts_with(crate::document_body_codec::MAGIC) {
194 if let Ok(fields) = crate::document_body_codec::decode(bytes) {
195 let mut object = Map::new();
196 for (key, value) in fields {
197 let json = match value {
198 Value::Integer(value) => JsonValue::Integer(value),
199 value => value.to_json(),
200 };
201 object.insert(key, json);
202 }
203 return JsonValue::Object(object);
204 }
205 }
206
207 json_from_slice::<JsonValue>(bytes).unwrap_or_else(|_| {
208 JsonValue::Object(
209 [
210 (
211 "code".to_string(),
212 JsonValue::String("INVALID_JSON".to_string()),
213 ),
214 ("hex".to_string(), JsonValue::String(hex_encode(bytes))),
215 ]
216 .into_iter()
217 .collect(),
218 )
219 })
220}
221
222fn format_mac(bytes: &[u8; 6]) -> String {
223 format!(
224 "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
225 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]
226 )
227}
228
229fn format_ipv4(ip: u32) -> String {
230 format!(
231 "{}.{}.{}.{}",
232 (ip >> 24) & 0xFF,
233 (ip >> 16) & 0xFF,
234 (ip >> 8) & 0xFF,
235 ip & 0xFF
236 )
237}
238
239fn hex_encode(bytes: &[u8]) -> String {
240 const HEX: &[u8; 16] = b"0123456789abcdef";
241 let mut encoded = String::with_capacity(bytes.len() * 2);
242 for byte in bytes {
243 encoded.push(char::from(HEX[usize::from(*byte >> 4)]));
244 encoded.push(char::from(HEX[usize::from(*byte & 0x0f)]));
245 }
246 encoded
247}
248
249#[cfg(test)]
250mod tests {
251 use std::net::{IpAddr, Ipv6Addr};
252
253 use crate::Value;
254
255 #[test]
256 fn every_value_variant_has_canonical_json() {
257 let cases = [
258 ("null", Value::Null, "null"),
259 ("integer", Value::Integer(42), "42"),
260 (
261 "large integer",
262 Value::Integer(9_007_199_254_740_992),
263 r#"{"$int":"9007199254740992"}"#,
264 ),
265 ("unsigned integer", Value::UnsignedInteger(7), "7"),
266 (
267 "large unsigned integer",
268 Value::UnsignedInteger(u64::MAX),
269 r#"{"$uint":"18446744073709551615"}"#,
270 ),
271 ("float", Value::Float(1.5), "1.5"),
272 ("text", Value::text("hello"), r#""hello""#),
273 ("blob", Value::Blob(vec![0x00, 0xff]), r#""00ff""#),
274 ("boolean", Value::Boolean(true), "true"),
275 ("timestamp", Value::Timestamp(1_700_000_000), "1700000000"),
276 ("duration", Value::Duration(-500), "-500"),
277 (
278 "IP address",
279 Value::IpAddr(IpAddr::V6(Ipv6Addr::LOCALHOST)),
280 r#""::1""#,
281 ),
282 (
283 "MAC address",
284 Value::MacAddr([0x00, 0x1a, 0x2b, 0x3c, 0x4d, 0x5e]),
285 r#""00:1a:2b:3c:4d:5e""#,
286 ),
287 ("vector", Value::Vector(vec![1.5, -2.0]), "[1.5,-2]"),
288 (
289 "JSON",
290 Value::Json(br#"{"nested":[1,2.5],"text":"ok"}"#.to_vec()),
291 r#"{"nested":[1,2.5],"text":"ok"}"#,
292 ),
293 (
294 "invalid JSON",
295 Value::Json(vec![0xff]),
296 r#"{"code":"INVALID_JSON","hex":"ff"}"#,
297 ),
298 (
299 "UUID",
300 Value::Uuid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]),
301 r#""000102030405060708090a0b0c0d0e0f""#,
302 ),
303 (
304 "node reference",
305 Value::NodeRef("node:1".into()),
306 r#""node:1""#,
307 ),
308 (
309 "edge reference",
310 Value::EdgeRef("edge:1".into()),
311 r#""edge:1""#,
312 ),
313 (
314 "vector reference",
315 Value::VectorRef("embeddings".into(), 7),
316 r#"{"collection":"embeddings","id":7}"#,
317 ),
318 (
319 "row reference",
320 Value::RowRef("users".into(), 8),
321 r#"{"row_id":8,"table":"users"}"#,
322 ),
323 ("color", Value::Color([0x12, 0xab, 0xff]), "\"#12ABFF\""),
324 ("email", Value::Email("a@b.test".into()), r#""a@b.test""#),
325 (
326 "URL",
327 Value::Url("https://example.test".into()),
328 r#""https://example.test""#,
329 ),
330 ("phone", Value::Phone(55_119_999), "55119999"),
331 ("semver", Value::Semver(1_002_003), r#""1.2.3""#),
332 ("CIDR", Value::Cidr(0xc0a8_0100, 24), r#""192.168.1.0/24""#),
333 ("date", Value::Date(20_000), "20000"),
334 ("time", Value::Time(3_723_000), "3723000"),
335 (
336 "decimal",
337 Value::Decimal(1_234_567),
338 r#"{"$decimal":"123.4567"}"#,
339 ),
340 (
341 "decimal text",
342 Value::DecimalText("3.141592653589793238462643383279".into()),
343 r#"{"$decimal":"3.141592653589793238462643383279"}"#,
344 ),
345 ("enum", Value::EnumValue(3), "3"),
346 (
347 "array",
348 Value::Array(vec![
349 Value::Boolean(false),
350 Value::Array(vec![Value::Integer(2)]),
351 ]),
352 "[false,[2]]",
353 ),
354 (
355 "millisecond timestamp",
356 Value::TimestampMs(1_700_000_000_123),
357 "1700000000123",
358 ),
359 ("IPv4", Value::Ipv4(0x7f00_0001), r#""127.0.0.1""#),
360 (
361 "IPv6",
362 Value::Ipv6(Ipv6Addr::LOCALHOST.octets()),
363 r#""::1""#,
364 ),
365 (
366 "subnet",
367 Value::Subnet(0x0a00_0000, 0xff00_0000),
368 r#""10.0.0.0/8""#,
369 ),
370 ("port", Value::Port(5432), "5432"),
371 ("latitude", Value::Latitude(12_345_678), "12.345678"),
372 ("longitude", Value::Longitude(-87_654_321), "-87.654321"),
373 (
374 "geo point",
375 Value::GeoPoint(12_345_678, -87_654_321),
376 r#""12.345678,-87.654321""#,
377 ),
378 ("country-2", Value::Country2(*b"BR"), r#""BR""#),
379 ("country-3", Value::Country3(*b"BRA"), r#""BRA""#),
380 ("language-2", Value::Lang2(*b"pt"), r#""pt""#),
381 ("language-5", Value::Lang5(*b"pt-BR"), r#""pt-BR""#),
382 ("currency", Value::Currency(*b"BRL"), r#""BRL""#),
383 ("asset code", Value::AssetCode("BTC".into()), r#""BTC""#),
384 (
385 "money",
386 Value::Money {
387 asset_code: "BRL".into(),
388 minor_units: 12_345,
389 scale: 2,
390 },
391 r#"{"asset_code":"BRL","minor_units":12345,"scale":2}"#,
392 ),
393 (
394 "color with alpha",
395 Value::ColorAlpha([0x12, 0xab, 0xff, 0x80]),
396 "\"#12ABFF80\"",
397 ),
398 (
399 "big integer",
400 Value::BigInt(i64::MIN),
401 r#"{"$int":"-9223372036854775808"}"#,
402 ),
403 (
404 "key reference",
405 Value::KeyRef("settings".into(), "theme".into()),
406 r#"{"collection":"settings","key":"theme"}"#,
407 ),
408 (
409 "document reference",
410 Value::DocRef("profiles".into(), 9),
411 r#"{"collection":"profiles","id":9}"#,
412 ),
413 (
414 "table reference",
415 Value::TableRef("users".into()),
416 r#""users""#,
417 ),
418 ("page reference", Value::PageRef(17), "17"),
419 ("secret", Value::Secret(vec![1, 2, 3]), r#""***""#),
420 ("password", Value::Password("hash".into()), r#""***""#),
421 ];
422
423 for (name, value, expected) in cases {
424 assert_eq!(value.to_json().to_string_compact(), expected, "{name}");
425 }
426 }
427}