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