1use std::borrow::Cow;
2use std::fmt;
3use std::io::{Read, Write};
4use std::ops::{Deref, DerefMut, Index, IndexMut};
5
6
7#[derive(Clone, Debug, PartialEq)]
8pub enum JsonNumber {
9 I64(i64),
10 U64(u64),
11 F64(f64),
12}
13
14
15impl JsonNumber {
16 pub fn from_i128(value: i128) -> Option<Self> {
17 if let Ok(value) = u64::try_from(value) {
18 Some(Self::U64(value))
19 } else if let Ok(value) = i64::try_from(value) {
20 Some(Self::I64(value))
21 } else {
22 None
23 }
24 }
25
26 pub fn from_u128(value: u128) -> Option<Self> {
27 u64::try_from(value).ok().map(Self::U64)
28 }
29
30 pub fn is_i64(&self) -> bool {
31 match self {
32 Self::I64(_) => true,
33 Self::U64(value) => *value <= i64::MAX as u64,
34 Self::F64(_) => false,
35 }
36 }
37
38 pub fn is_u64(&self) -> bool {
39 matches!(self, Self::U64(_))
40 }
41
42 pub fn is_f64(&self) -> bool {
43 matches!(self, Self::F64(_))
44 }
45
46 pub fn as_i64(&self) -> Option<i64> {
47 match self {
48 Self::I64(value) => Some(*value),
49 Self::U64(value) => (*value <= i64::MAX as u64).then_some(*value as i64),
50 Self::F64(_) => None,
51 }
52 }
53
54 pub fn as_i128(&self) -> Option<i128> {
55 match self {
56 Self::I64(value) => Some(*value as i128),
57 Self::U64(value) => Some(*value as i128),
58 Self::F64(_) => None,
59 }
60 }
61
62 pub fn as_u64(&self) -> Option<u64> {
63 match self {
64 Self::I64(value) => (*value >= 0).then_some(*value as u64),
65 Self::U64(value) => Some(*value),
66 Self::F64(_) => None,
67 }
68 }
69
70 pub fn as_u128(&self) -> Option<u128> {
71 match self {
72 Self::I64(value) => (*value >= 0).then_some(*value as u128),
73 Self::U64(value) => Some(*value as u128),
74 Self::F64(_) => None,
75 }
76 }
77
78 pub fn as_f64(&self) -> Option<f64> {
79 match self {
80 Self::I64(value) => Some(*value as f64),
81 Self::U64(value) => Some(*value as f64),
82 Self::F64(value) => Some(*value),
83 }
84 }
85
86 pub fn from_f64(value: f64) -> Option<Self> {
87 value.is_finite().then_some(Self::F64(value))
88 }
89}
90
91#[derive(Clone, Debug, PartialEq)]
92pub enum JsonValue {
93 Null,
94 Bool(bool),
95 Number(JsonNumber),
96 String(String),
97 Array(Vec<JsonValue>),
98 Object(Map),
99}
100
101pub type Value = JsonValue;
102pub type Number = JsonNumber;
103
104#[derive(Clone, Debug, PartialEq)]
105pub struct Map(Vec<(String, JsonValue)>);
106
107impl Map {
108 pub fn new() -> Self {
109 Self(Vec::new())
110 }
111
112 pub fn keys(&self) -> impl ExactSizeIterator<Item = &String> {
113 self.0.iter().map(|(key, _)| key)
114 }
115}
116
117impl Default for Map {
118 fn default() -> Self {
119 Self::new()
120 }
121}
122
123impl From<Vec<(String, JsonValue)>> for Map {
124 fn from(value: Vec<(String, JsonValue)>) -> Self {
125 Self(value)
126 }
127}
128
129
130impl std::iter::FromIterator<(String, JsonValue)> for Map {
131 fn from_iter<T: IntoIterator<Item = (String, JsonValue)>>(iter: T) -> Self {
132 Self(iter.into_iter().collect())
133 }
134}
135
136impl Deref for Map {
137 type Target = Vec<(String, JsonValue)>;
138
139 fn deref(&self) -> &Self::Target {
140 &self.0
141 }
142}
143
144impl DerefMut for Map {
145 fn deref_mut(&mut self) -> &mut Self::Target {
146 &mut self.0
147 }
148}
149
150#[derive(Clone, Debug, PartialEq)]
151pub enum BorrowedJsonValue<'a> {
152 Null,
153 Bool(bool),
154 Number(JsonNumber),
155 String(Cow<'a, str>),
156 Array(Vec<BorrowedJsonValue<'a>>),
157 Object(Vec<(Cow<'a, str>, BorrowedJsonValue<'a>)>),
158}
159
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct CompiledObjectSchema {
162 fields: Vec<CompiledField>,
163 capacity_hint: usize,
164}
165
166#[derive(Clone, Debug, PartialEq, Eq)]
167pub struct CompiledRowSchema {
168 object: CompiledObjectSchema,
169 row_capacity_hint: usize,
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct JsonTape {
174 pub tokens: Vec<TapeToken>,
175}
176
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct TapeToken {
179 pub kind: TapeTokenKind,
180 pub start: usize,
181 pub end: usize,
182 pub parent: Option<usize>,
183}
184
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub enum TapeTokenKind {
187 Null,
188 Bool,
189 Number,
190 String,
191 Key,
192 Array,
193 Object,
194}
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct TapeValue<'a> {
198 tape: &'a JsonTape,
199 input: &'a str,
200 index: usize,
201}
202
203#[derive(Clone, Debug, PartialEq, Eq)]
204pub struct TapeObjectIndex {
205 buckets: Vec<Vec<(u64, usize, usize)>>,
206}
207
208#[derive(Clone, Copy, Debug)]
209pub struct IndexedTapeObject<'a> {
210 object: TapeValue<'a>,
211 index: &'a TapeObjectIndex,
212}
213
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub struct CompiledTapeKey {
216 key: String,
217 hash: u64,
218}
219
220#[derive(Clone, Debug, PartialEq, Eq)]
221pub struct CompiledTapeKeys {
222 keys: Vec<CompiledTapeKey>,
223}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
226struct CompiledField {
227 key: String,
228 rendered_prefix: Vec<u8>,
229}
230
231#[derive(Clone, Debug, PartialEq, Eq)]
232pub enum JsonError {
233 NonFiniteNumber,
234 Io,
235}
236
237#[derive(Clone, Debug, PartialEq, Eq)]
238pub enum JsonParseError {
239 InvalidUtf8,
240 UnexpectedEnd,
241 UnexpectedTrailingCharacters(usize),
242 UnexpectedCharacter { index: usize, found: char },
243 InvalidLiteral { index: usize },
244 InvalidNumber { index: usize },
245 InvalidEscape { index: usize },
246 InvalidUnicodeEscape { index: usize },
247 InvalidUnicodeScalar { index: usize },
248 ExpectedColon { index: usize },
249 ExpectedCommaOrEnd { index: usize, context: &'static str },
250}
251
252impl fmt::Display for JsonError {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 match self {
255 Self::NonFiniteNumber => {
256 f.write_str("cannot serialize non-finite floating-point value")
257 }
258 Self::Io => f.write_str("i/o error while serializing JSON"),
259 }
260 }
261}
262
263impl fmt::Display for JsonParseError {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 match self {
266 Self::InvalidUtf8 => f.write_str("input is not valid UTF-8"),
267 Self::UnexpectedEnd => f.write_str("unexpected end of JSON input"),
268 Self::UnexpectedTrailingCharacters(index) => {
269 write!(f, "unexpected trailing characters at byte {index}")
270 }
271 Self::UnexpectedCharacter { index, found } => {
272 write!(f, "unexpected character '{found}' at byte {index}")
273 }
274 Self::InvalidLiteral { index } => write!(f, "invalid literal at byte {index}"),
275 Self::InvalidNumber { index } => write!(f, "invalid number at byte {index}"),
276 Self::InvalidEscape { index } => write!(f, "invalid escape sequence at byte {index}"),
277 Self::InvalidUnicodeEscape { index } => {
278 write!(f, "invalid unicode escape at byte {index}")
279 }
280 Self::InvalidUnicodeScalar { index } => {
281 write!(f, "invalid unicode scalar at byte {index}")
282 }
283 Self::ExpectedColon { index } => write!(f, "expected ':' at byte {index}"),
284 Self::ExpectedCommaOrEnd { index, context } => {
285 write!(f, "expected ',' or end of {context} at byte {index}")
286 }
287 }
288 }
289}
290
291impl fmt::Display for JsonNumber {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 match self {
294 Self::I64(value) => write!(f, "{value}"),
295 Self::U64(value) => write!(f, "{value}"),
296 Self::F64(value) => write!(f, "{value}"),
297 }
298 }
299}
300
301
302impl From<i64> for JsonNumber {
303 fn from(value: i64) -> Self {
304 if value >= 0 {
305 Self::U64(value as u64)
306 } else {
307 Self::I64(value)
308 }
309 }
310}
311
312impl From<u64> for JsonNumber {
313 fn from(value: u64) -> Self {
314 Self::U64(value)
315 }
316}
317
318
319impl std::error::Error for JsonError {}
320impl std::error::Error for JsonParseError {}
321
322impl JsonValue {
323 pub fn object(entries: Vec<(impl Into<String>, JsonValue)>) -> Self {
324 Self::Object(
325 entries
326 .into_iter()
327 .map(|(key, value)| (key.into(), value))
328 .collect::<Vec<_>>().into(),
329 )
330 }
331
332 pub fn array(values: Vec<JsonValue>) -> Self {
333 Self::Array(values)
334 }
335
336 pub fn to_json_string(&self) -> Result<String, JsonError> {
337 let mut out = Vec::with_capacity(initial_json_capacity(self));
338 write_json_value(&mut out, self)?;
339 Ok(unsafe { String::from_utf8_unchecked(out) })
340 }
341
342 pub fn push_field(&mut self, key: impl Into<String>, value: impl Into<JsonValue>) {
343 match self {
344 Self::Object(entries) => entries.push((key.into(), value.into())),
345 _ => panic!("push_field called on non-object JSON value"),
346 }
347 }
348
349 pub fn push_item(&mut self, value: impl Into<JsonValue>) {
350 match self {
351 Self::Array(values) => values.push(value.into()),
352 _ => panic!("push_item called on non-array JSON value"),
353 }
354 }
355
356 pub fn is_null(&self) -> bool {
357 self.as_null().is_some()
358 }
359
360 pub fn as_null(&self) -> Option<()> {
361 matches!(self, Self::Null).then_some(())
362 }
363
364 pub fn is_boolean(&self) -> bool {
365 matches!(self, Self::Bool(_))
366 }
367
368 pub fn is_number(&self) -> bool {
369 matches!(self, Self::Number(_))
370 }
371
372 pub fn is_string(&self) -> bool {
373 matches!(self, Self::String(_))
374 }
375
376 pub fn is_array(&self) -> bool {
377 matches!(self, Self::Array(_))
378 }
379
380 pub fn is_object(&self) -> bool {
381 matches!(self, Self::Object(_))
382 }
383
384 pub fn as_bool(&self) -> Option<bool> {
385 match self {
386 Self::Bool(value) => Some(*value),
387 _ => None,
388 }
389 }
390
391 pub fn as_number(&self) -> Option<&JsonNumber> {
392 match self {
393 Self::Number(number) => Some(number),
394 _ => None,
395 }
396 }
397
398 pub fn is_i64(&self) -> bool {
399 self.as_number().is_some_and(JsonNumber::is_i64)
400 }
401
402 pub fn is_u64(&self) -> bool {
403 self.as_number().is_some_and(JsonNumber::is_u64)
404 }
405
406 pub fn is_f64(&self) -> bool {
407 self.as_number().is_some_and(JsonNumber::is_f64)
408 }
409
410 pub fn as_i64(&self) -> Option<i64> {
411 self.as_number().and_then(JsonNumber::as_i64)
412 }
413
414 pub fn as_u64(&self) -> Option<u64> {
415 self.as_number().and_then(JsonNumber::as_u64)
416 }
417
418 pub fn as_f64(&self) -> Option<f64> {
419 self.as_number().and_then(JsonNumber::as_f64)
420 }
421
422 pub fn as_str(&self) -> Option<&str> {
423 match self {
424 Self::String(value) => Some(value.as_str()),
425 _ => None,
426 }
427 }
428
429 pub fn as_array(&self) -> Option<&Vec<JsonValue>> {
430 match self {
431 Self::Array(values) => Some(values),
432 _ => None,
433 }
434 }
435
436 pub fn as_array_mut(&mut self) -> Option<&mut Vec<JsonValue>> {
437 match self {
438 Self::Array(values) => Some(values),
439 _ => None,
440 }
441 }
442
443 pub fn as_object(&self) -> Option<&Map> {
444 match self {
445 Self::Object(entries) => Some(entries),
446 _ => None,
447 }
448 }
449
450 pub fn as_object_mut(&mut self) -> Option<&mut Map> {
451 match self {
452 Self::Object(entries) => Some(entries),
453 _ => None,
454 }
455 }
456
457 pub fn get<I>(&self, index: I) -> Option<&JsonValue>
458 where
459 I: ValueIndex,
460 {
461 index.index_into(self)
462 }
463
464 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut JsonValue>
465 where
466 I: ValueIndex,
467 {
468 index.index_into_mut(self)
469 }
470
471 pub fn len(&self) -> usize {
472 match self {
473 Self::Array(values) => values.len(),
474 Self::Object(entries) => entries.len(),
475 _ => 0,
476 }
477 }
478
479 pub fn is_empty(&self) -> bool {
480 self.len() == 0
481 }
482
483 pub fn as_i128(&self) -> Option<i128> {
484 self.as_i64().map(|v| v as i128)
485 }
486
487 pub fn as_u128(&self) -> Option<u128> {
488 self.as_u64().map(|v| v as u128)
489 }
490
491 pub fn as_f32(&self) -> Option<f32> {
492 self.as_f64().map(|v| v as f32)
493 }
494
495 pub fn get_index(&self, index: usize) -> Option<&JsonValue> {
496 match self {
497 Self::Array(values) => values.get(index),
498 _ => None,
499 }
500 }
501
502 pub fn get_index_mut(&mut self, index: usize) -> Option<&mut JsonValue> {
503 match self {
504 Self::Array(values) => values.get_mut(index),
505 _ => None,
506 }
507 }
508
509 pub fn take(&mut self) -> JsonValue {
510 std::mem::replace(self, JsonValue::Null)
511 }
512
513 pub fn pointer(&self, pointer: &str) -> Option<&JsonValue> {
514 if pointer.is_empty() {
515 return Some(self);
516 }
517 if !pointer.starts_with('/') {
518 return None;
519 }
520 let mut current = self;
521 for segment in pointer.split('/').skip(1) {
522 let token = decode_pointer_segment(segment);
523 current = match current {
524 JsonValue::Object(entries) => entries
525 .iter()
526 .find(|(key, _)| key == &token)
527 .map(|(_, value)| value)?,
528 JsonValue::Array(values) => values.get(token.parse::<usize>().ok()?)?,
529 _ => return None,
530 };
531 }
532 Some(current)
533 }
534
535 pub fn pointer_mut(&mut self, pointer: &str) -> Option<&mut JsonValue> {
536 if pointer.is_empty() {
537 return Some(self);
538 }
539 if !pointer.starts_with('/') {
540 return None;
541 }
542 let mut current = self;
543 for segment in pointer.split('/').skip(1) {
544 let token = decode_pointer_segment(segment);
545 current = match current {
546 JsonValue::Object(entries) => entries
547 .iter_mut()
548 .find(|(key, _)| key == &token)
549 .map(|(_, value)| value)?,
550 JsonValue::Array(values) => values.get_mut(token.parse::<usize>().ok()?)?,
551 _ => return None,
552 };
553 }
554 Some(current)
555 }
556
557 pub fn sort_all_objects(&mut self) {
558 match self {
559 JsonValue::Object(entries) => {
560 entries.sort_by(|a, b| a.0.cmp(&b.0));
561 for (_, value) in entries.iter_mut() {
562 value.sort_all_objects();
563 }
564 }
565 JsonValue::Array(values) => {
566 for value in values.iter_mut() {
567 value.sort_all_objects();
568 }
569 }
570 _ => {}
571 }
572 }
573}
574
575impl<'a> BorrowedJsonValue<'a> {
576 pub fn into_owned(self) -> JsonValue {
577 match self {
578 Self::Null => JsonValue::Null,
579 Self::Bool(value) => JsonValue::Bool(value),
580 Self::Number(value) => JsonValue::Number(value),
581 Self::String(value) => JsonValue::String(value.into_owned()),
582 Self::Array(values) => JsonValue::Array(
583 values
584 .into_iter()
585 .map(BorrowedJsonValue::into_owned)
586 .collect(),
587 ),
588 Self::Object(entries) => JsonValue::Object(
589 entries
590 .into_iter()
591 .map(|(key, value)| (key.into_owned(), value.into_owned()))
592 .collect(),
593 ),
594 }
595 }
596}
597
598impl CompiledObjectSchema {
599 pub fn new(keys: &[&str]) -> Self {
600 let mut fields = Vec::with_capacity(keys.len());
601 let mut capacity_hint = 2;
602 for (index, key) in keys.iter().enumerate() {
603 let mut rendered_prefix = Vec::with_capacity(key.len() + 4);
604 if index > 0 {
605 rendered_prefix.push(b',');
606 }
607 write_json_key(&mut rendered_prefix, key);
608 capacity_hint += rendered_prefix.len() + 8;
609 fields.push(CompiledField {
610 key: (*key).to_owned(),
611 rendered_prefix,
612 });
613 }
614 Self {
615 fields,
616 capacity_hint,
617 }
618 }
619
620 pub fn keys(&self) -> impl ExactSizeIterator<Item = &str> {
621 self.fields.iter().map(|field| field.key.as_str())
622 }
623
624 pub fn to_json_string<'a, I>(&self, values: I) -> Result<String, JsonError>
625 where
626 I: IntoIterator<Item = &'a JsonValue>,
627 {
628 let mut out = Vec::with_capacity(self.capacity_hint);
629 self.write_json_bytes(&mut out, values)?;
630 Ok(unsafe { String::from_utf8_unchecked(out) })
631 }
632
633 pub fn write_json_bytes<'a, I>(&self, out: &mut Vec<u8>, values: I) -> Result<(), JsonError>
634 where
635 I: IntoIterator<Item = &'a JsonValue>,
636 {
637 out.push(b'{');
638 let mut iter = values.into_iter();
639 for field in &self.fields {
640 let Some(value) = iter.next() else {
641 panic!(
642 "compiled object schema expected {} values",
643 self.fields.len()
644 );
645 };
646 out.extend_from_slice(&field.rendered_prefix);
647 write_json_value(out, value)?;
648 }
649 if iter.next().is_some() {
650 panic!(
651 "compiled object schema received more than {} values",
652 self.fields.len()
653 );
654 }
655 out.push(b'}');
656 Ok(())
657 }
658}
659
660impl CompiledRowSchema {
661 pub fn new(keys: &[&str]) -> Self {
662 let object = CompiledObjectSchema::new(keys);
663 let row_capacity_hint = object.capacity_hint;
664 Self {
665 object,
666 row_capacity_hint,
667 }
668 }
669
670 pub fn object_schema(&self) -> &CompiledObjectSchema {
671 &self.object
672 }
673
674 pub fn to_json_string<'a, R, I>(&self, rows: R) -> Result<String, JsonError>
675 where
676 R: IntoIterator<Item = I>,
677 I: IntoIterator<Item = &'a JsonValue>,
678 {
679 let iter = rows.into_iter();
680 let (lower, _) = iter.size_hint();
681 let mut out = Vec::with_capacity(2 + lower.saturating_mul(self.row_capacity_hint + 1));
682 self.write_json_bytes_from_iter(&mut out, iter)?;
683 Ok(unsafe { String::from_utf8_unchecked(out) })
684 }
685
686 pub fn write_json_bytes<'a, R, I>(&self, out: &mut Vec<u8>, rows: R) -> Result<(), JsonError>
687 where
688 R: IntoIterator<Item = I>,
689 I: IntoIterator<Item = &'a JsonValue>,
690 {
691 self.write_json_bytes_from_iter(out, rows.into_iter())
692 }
693
694 pub fn write_row_json_bytes<'a, I>(&self, out: &mut Vec<u8>, values: I) -> Result<(), JsonError>
695 where
696 I: IntoIterator<Item = &'a JsonValue>,
697 {
698 self.object.write_json_bytes(out, values)
699 }
700
701 fn write_json_bytes_from_iter<'a, R, I>(
702 &self,
703 out: &mut Vec<u8>,
704 mut rows: R,
705 ) -> Result<(), JsonError>
706 where
707 R: Iterator<Item = I>,
708 I: IntoIterator<Item = &'a JsonValue>,
709 {
710 out.push(b'[');
711 if let Some(first_row) = rows.next() {
712 self.object.write_json_bytes(out, first_row)?;
713 for row in rows {
714 out.push(b',');
715 self.object.write_json_bytes(out, row)?;
716 }
717 }
718 out.push(b']');
719 Ok(())
720 }
721}
722
723impl From<bool> for JsonValue {
724 fn from(value: bool) -> Self {
725 Self::Bool(value)
726 }
727}
728
729impl From<String> for JsonValue {
730 fn from(value: String) -> Self {
731 Self::String(value)
732 }
733}
734
735impl From<&str> for JsonValue {
736 fn from(value: &str) -> Self {
737 Self::String(value.to_owned())
738 }
739}
740
741impl From<i8> for JsonValue {
742 fn from(value: i8) -> Self {
743 Self::Number(JsonNumber::from(value as i64))
744 }
745}
746
747impl From<i16> for JsonValue {
748 fn from(value: i16) -> Self {
749 Self::Number(JsonNumber::from(value as i64))
750 }
751}
752
753impl From<i32> for JsonValue {
754 fn from(value: i32) -> Self {
755 Self::Number(JsonNumber::from(value as i64))
756 }
757}
758
759impl From<i64> for JsonValue {
760 fn from(value: i64) -> Self {
761 Self::Number(JsonNumber::from(value))
762 }
763}
764
765impl From<isize> for JsonValue {
766 fn from(value: isize) -> Self {
767 Self::Number(JsonNumber::from(value as i64))
768 }
769}
770
771impl From<u8> for JsonValue {
772 fn from(value: u8) -> Self {
773 Self::Number(JsonNumber::U64(value as u64))
774 }
775}
776
777impl From<u16> for JsonValue {
778 fn from(value: u16) -> Self {
779 Self::Number(JsonNumber::U64(value as u64))
780 }
781}
782
783impl From<u32> for JsonValue {
784 fn from(value: u32) -> Self {
785 Self::Number(JsonNumber::U64(value as u64))
786 }
787}
788
789impl From<u64> for JsonValue {
790 fn from(value: u64) -> Self {
791 Self::Number(JsonNumber::U64(value))
792 }
793}
794
795impl From<usize> for JsonValue {
796 fn from(value: usize) -> Self {
797 Self::Number(JsonNumber::U64(value as u64))
798 }
799}
800
801impl From<f32> for JsonValue {
802 fn from(value: f32) -> Self {
803 Self::Number(JsonNumber::F64(value as f64))
804 }
805}
806
807impl From<f64> for JsonValue {
808 fn from(value: f64) -> Self {
809 Self::Number(JsonNumber::F64(value))
810 }
811}
812
813impl From<i128> for JsonValue {
814 fn from(value: i128) -> Self {
815 JsonNumber::from_i128(value)
816 .map(Self::Number)
817 .unwrap_or_else(|| Self::String(value.to_string()))
818 }
819}
820
821impl From<u128> for JsonValue {
822 fn from(value: u128) -> Self {
823 JsonNumber::from_u128(value)
824 .map(Self::Number)
825 .unwrap_or_else(|| Self::String(value.to_string()))
826 }
827}
828
829impl<T> From<Option<T>> for JsonValue
830where
831 T: Into<JsonValue>,
832{
833 fn from(value: Option<T>) -> Self {
834 match value {
835 Some(value) => value.into(),
836 None => Self::Null,
837 }
838 }
839}
840
841impl<T> From<Vec<T>> for JsonValue
842where
843 T: Into<JsonValue>,
844{
845 fn from(values: Vec<T>) -> Self {
846 Self::Array(values.into_iter().map(Into::into).collect())
847 }
848}
849
850
851impl<K, V> std::iter::FromIterator<(K, V)> for JsonValue
852where
853 K: Into<String>,
854 V: Into<JsonValue>,
855{
856 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
857 Self::Object(
858 iter.into_iter()
859 .map(|(key, value)| (key.into(), value.into()))
860 .collect::<Vec<_>>().into(),
861 )
862 }
863}
864
865impl<T> std::iter::FromIterator<T> for JsonValue
866where
867 T: Into<JsonValue>,
868{
869 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
870 Self::Array(iter.into_iter().map(Into::into).collect())
871 }
872}
873
874pub fn escape_json_string(input: &str) -> String {
875 let mut out = Vec::with_capacity(input.len() + 2);
876 write_escaped_json_string(&mut out, input);
877 unsafe { String::from_utf8_unchecked(out) }
878}
879
880pub fn parse_json(input: &str) -> Result<JsonValue, JsonParseError> {
881 let mut parser = Parser::new(input);
882 let value = parser.parse_value()?;
883 parser.skip_whitespace();
884 if parser.is_eof() {
885 Ok(value)
886 } else {
887 Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
888 }
889}
890
891pub fn parse_json_borrowed(input: &str) -> Result<BorrowedJsonValue<'_>, JsonParseError> {
892 let mut parser = Parser::new(input);
893 let value = parser.parse_value_borrowed()?;
894 parser.skip_whitespace();
895 if parser.is_eof() {
896 Ok(value)
897 } else {
898 Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
899 }
900}
901
902pub fn parse_json_tape(input: &str) -> Result<JsonTape, JsonParseError> {
903 let mut parser = Parser::new(input);
904 let mut tokens = Vec::new();
905 parser.parse_tape_value(&mut tokens, None)?;
906 parser.skip_whitespace();
907 if parser.is_eof() {
908 Ok(JsonTape { tokens })
909 } else {
910 Err(JsonParseError::UnexpectedTrailingCharacters(parser.index))
911 }
912}
913
914
915pub fn from_str(input: &str) -> Result<JsonValue, JsonParseError> {
916 parse_json(input)
917}
918
919pub fn from_slice(input: &[u8]) -> Result<JsonValue, JsonParseError> {
920 let input = std::str::from_utf8(input).map_err(|_| JsonParseError::InvalidUtf8)?;
921 parse_json(input)
922}
923
924pub fn to_string(value: &JsonValue) -> Result<String, JsonError> {
925 value.to_json_string()
926}
927
928pub fn to_vec(value: &JsonValue) -> Result<Vec<u8>, JsonError> {
929 let mut out = Vec::with_capacity(initial_json_capacity(value));
930 write_json_value(&mut out, value)?;
931 Ok(out)
932}
933
934pub fn from_reader<R: Read>(mut reader: R) -> Result<JsonValue, JsonParseError> {
935 let mut input = String::new();
936 reader
937 .read_to_string(&mut input)
938 .map_err(|_| JsonParseError::InvalidUtf8)?;
939 parse_json(&input)
940}
941
942pub fn to_writer<W: Write>(mut writer: W, value: &JsonValue) -> Result<(), JsonError> {
943 let bytes = to_vec(value)?;
944 writer.write_all(&bytes).map_err(|_| JsonError::Io)
945}
946
947pub fn to_string_pretty(value: &JsonValue) -> Result<String, JsonError> {
948 let mut out = Vec::with_capacity(initial_json_capacity(value) + 16);
949 write_json_value_pretty(&mut out, value, 0)?;
950 Ok(unsafe { String::from_utf8_unchecked(out) })
951}
952
953pub fn to_vec_pretty(value: &JsonValue) -> Result<Vec<u8>, JsonError> {
954 let mut out = Vec::with_capacity(initial_json_capacity(value) + 16);
955 write_json_value_pretty(&mut out, value, 0)?;
956 Ok(out)
957}
958
959pub fn to_writer_pretty<W: Write>(mut writer: W, value: &JsonValue) -> Result<(), JsonError> {
960 let bytes = to_vec_pretty(value)?;
961 writer.write_all(&bytes).map_err(|_| JsonError::Io)
962}
963
964impl JsonTape {
965 pub fn root<'a>(&'a self, input: &'a str) -> Option<TapeValue<'a>> {
966 (!self.tokens.is_empty()).then_some(TapeValue {
967 tape: self,
968 input,
969 index: 0,
970 })
971 }
972}
973
974impl<'a> TapeValue<'a> {
975 pub fn kind(&self) -> TapeTokenKind {
976 self.tape.tokens[self.index].kind
977 }
978
979 pub fn as_str(&self) -> Option<&'a str> {
980 let token = &self.tape.tokens[self.index];
981 match token.kind {
982 TapeTokenKind::String | TapeTokenKind::Key => {
983 if self.input.as_bytes()[token.start] == b'"'
984 && self.input.as_bytes()[token.end - 1] == b'"'
985 {
986 Some(&self.input[token.start + 1..token.end - 1])
987 } else {
988 None
989 }
990 }
991 _ => None,
992 }
993 }
994
995 pub fn get(&self, key: &str) -> Option<TapeValue<'a>> {
996 if self.kind() != TapeTokenKind::Object {
997 return None;
998 }
999 self.get_linear(key)
1000 }
1001
1002 pub fn build_object_index(&self) -> Option<TapeObjectIndex> {
1003 if self.kind() != TapeTokenKind::Object {
1004 return None;
1005 }
1006 let parent = self.index;
1007 let tokens = &self.tape.tokens;
1008 let mut entries = Vec::new();
1009 let mut i = self.index + 1;
1010 while i + 1 < tokens.len() {
1011 if tokens[i].parent != Some(parent) {
1012 i += 1;
1013 continue;
1014 }
1015 if tokens[i].kind == TapeTokenKind::Key && tokens[i + 1].parent == Some(parent) {
1016 let candidate = TapeValue {
1017 tape: self.tape,
1018 input: self.input,
1019 index: i,
1020 };
1021 let key = candidate.as_str().unwrap_or("");
1022 let hash = hash_key(key.as_bytes());
1023 entries.push((hash, i, i + 1));
1024 i += 2;
1025 } else {
1026 i += 1;
1027 }
1028 }
1029 let bucket_count = (entries.len().next_power_of_two().max(1)) * 2;
1030 let mut buckets = vec![Vec::new(); bucket_count];
1031 for entry in entries {
1032 let bucket = (entry.0 as usize) & (bucket_count - 1);
1033 buckets[bucket].push(entry);
1034 }
1035 Some(TapeObjectIndex { buckets })
1036 }
1037
1038 pub fn with_index<'b>(&'b self, index: &'b TapeObjectIndex) -> IndexedTapeObject<'b> {
1039 IndexedTapeObject {
1040 object: TapeValue {
1041 tape: self.tape,
1042 input: self.input,
1043 index: self.index,
1044 },
1045 index,
1046 }
1047 }
1048
1049 fn get_linear(&self, key: &str) -> Option<TapeValue<'a>> {
1050 let parent = self.index;
1051 let tokens = &self.tape.tokens;
1052 let mut i = self.index + 1;
1053 while i < tokens.len() {
1054 if tokens[i].parent != Some(parent) {
1055 i += 1;
1056 continue;
1057 }
1058 if tokens[i].kind != TapeTokenKind::Key {
1059 i += 1;
1060 continue;
1061 }
1062 let candidate = TapeValue {
1063 tape: self.tape,
1064 input: self.input,
1065 index: i,
1066 };
1067 if candidate.as_str() == Some(key) {
1068 let value_index = i + 1;
1069 if value_index < tokens.len() && tokens[value_index].parent == Some(parent) {
1070 return Some(TapeValue {
1071 tape: self.tape,
1072 input: self.input,
1073 index: value_index,
1074 });
1075 }
1076 return None;
1077 }
1078 i += 1;
1079 }
1080 None
1081 }
1082}
1083
1084impl TapeObjectIndex {
1085 pub fn get<'a>(&self, object: TapeValue<'a>, key: &str) -> Option<TapeValue<'a>> {
1086 self.get_hashed(object, hash_key(key.as_bytes()), key)
1087 }
1088
1089 pub fn get_compiled<'a>(&self, object: TapeValue<'a>, key: &CompiledTapeKey) -> Option<TapeValue<'a>> {
1090 self.get_hashed(object, key.hash, &key.key)
1091 }
1092
1093 fn get_hashed<'a>(&self, object: TapeValue<'a>, hash: u64, key: &str) -> Option<TapeValue<'a>> {
1094 let bucket = (hash as usize) & (self.buckets.len() - 1);
1095 for (entry_hash, key_index, value_index) in &self.buckets[bucket] {
1096 if *entry_hash != hash {
1097 continue;
1098 }
1099 let candidate = TapeValue {
1100 tape: object.tape,
1101 input: object.input,
1102 index: *key_index,
1103 };
1104 if candidate.as_str() == Some(key) {
1105 return Some(TapeValue {
1106 tape: object.tape,
1107 input: object.input,
1108 index: *value_index,
1109 });
1110 }
1111 }
1112 None
1113 }
1114}
1115
1116impl CompiledTapeKey {
1117 pub fn new(key: impl Into<String>) -> Self {
1118 let key = key.into();
1119 let hash = hash_key(key.as_bytes());
1120 Self { key, hash }
1121 }
1122
1123 pub fn as_str(&self) -> &str {
1124 &self.key
1125 }
1126}
1127
1128impl CompiledTapeKeys {
1129 pub fn new(keys: &[&str]) -> Self {
1130 Self {
1131 keys: keys.iter().map(|key| CompiledTapeKey::new(*key)).collect(),
1132 }
1133 }
1134
1135 pub fn iter(&self) -> impl Iterator<Item = &CompiledTapeKey> {
1136 self.keys.iter()
1137 }
1138}
1139
1140impl<'a> IndexedTapeObject<'a> {
1141 pub fn get(&self, key: &str) -> Option<TapeValue<'a>> {
1142 self.index.get(self.object, key)
1143 }
1144
1145 pub fn get_compiled(&self, key: &CompiledTapeKey) -> Option<TapeValue<'a>> {
1146 self.index.get_compiled(self.object, key)
1147 }
1148
1149 pub fn get_many<'b>(
1150 &'b self,
1151 keys: &'b [&'b str],
1152 ) -> impl Iterator<Item = Option<TapeValue<'a>>> + 'b {
1153 keys.iter().map(|key| self.get(key))
1154 }
1155
1156 pub fn get_compiled_many<'b>(
1157 &'b self,
1158 keys: &'b CompiledTapeKeys,
1159 ) -> impl Iterator<Item = Option<TapeValue<'a>>> + 'b {
1160 keys.iter().map(|key| self.get_compiled(key))
1161 }
1162}
1163
1164
1165impl fmt::Display for JsonValue {
1166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167 match self.to_json_string() {
1168 Ok(json) => f.write_str(&json),
1169 Err(_) => Err(fmt::Error),
1170 }
1171 }
1172}
1173
1174static JSON_NULL: JsonValue = JsonValue::Null;
1175
1176pub trait ValueIndex {
1177 fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue>;
1178 fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue>;
1179}
1180
1181impl ValueIndex for usize {
1182 fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1183 match value {
1184 JsonValue::Array(values) => values.get(*self),
1185 _ => None,
1186 }
1187 }
1188
1189 fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1190 match value {
1191 JsonValue::Array(values) => values.get_mut(*self),
1192 _ => None,
1193 }
1194 }
1195}
1196
1197impl ValueIndex for str {
1198 fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1199 match value {
1200 JsonValue::Object(entries) => object_get(entries, self),
1201 _ => None,
1202 }
1203 }
1204
1205 fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1206 match value {
1207 JsonValue::Object(entries) => object_get_mut(entries, self),
1208 _ => None,
1209 }
1210 }
1211}
1212
1213impl ValueIndex for String {
1214 fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1215 self.as_str().index_into(value)
1216 }
1217
1218 fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1219 self.as_str().index_into_mut(value)
1220 }
1221}
1222
1223impl<T> ValueIndex for &T
1224where
1225 T: ?Sized + ValueIndex,
1226{
1227 fn index_into<'a>(&self, value: &'a JsonValue) -> Option<&'a JsonValue> {
1228 (**self).index_into(value)
1229 }
1230
1231 fn index_into_mut<'a>(&self, value: &'a mut JsonValue) -> Option<&'a mut JsonValue> {
1232 (**self).index_into_mut(value)
1233 }
1234}
1235
1236fn object_get<'a>(entries: &'a [(String, JsonValue)], key: &str) -> Option<&'a JsonValue> {
1237 entries
1238 .iter()
1239 .find(|(candidate, _)| candidate == key)
1240 .map(|(_, value)| value)
1241}
1242
1243fn object_get_mut<'a>(entries: &'a mut Vec<(String, JsonValue)>, key: &str) -> Option<&'a mut JsonValue> {
1244 entries
1245 .iter_mut()
1246 .find(|(candidate, _)| candidate == key)
1247 .map(|(_, value)| value)
1248}
1249
1250fn object_index_or_insert<'a>(value: &'a mut JsonValue, key: &str) -> &'a mut JsonValue {
1251 if matches!(value, JsonValue::Null) {
1252 *value = JsonValue::Object(Map::new());
1253 }
1254 match value {
1255 JsonValue::Object(entries) => {
1256 if let Some(pos) = entries.iter().position(|(candidate, _)| candidate == key) {
1257 &mut entries[pos].1
1258 } else {
1259 entries.push((key.to_owned(), JsonValue::Null));
1260 &mut entries.last_mut().unwrap().1
1261 }
1262 }
1263 JsonValue::Null => unreachable!(),
1264 JsonValue::Bool(_) => panic!("cannot access key {:?} in JSON boolean", key),
1265 JsonValue::Number(_) => panic!("cannot access key {:?} in JSON number", key),
1266 JsonValue::String(_) => panic!("cannot access key {:?} in JSON string", key),
1267 JsonValue::Array(_) => panic!("cannot access key {:?} in JSON array", key),
1268 }
1269}
1270
1271fn array_index_or_panic(value: &mut JsonValue, index: usize) -> &mut JsonValue {
1272 match value {
1273 JsonValue::Array(values) => {
1274 let len = values.len();
1275 values.get_mut(index).unwrap_or_else(|| panic!("cannot access index {} of JSON array of length {}", index, len))
1276 }
1277 JsonValue::Null => panic!("cannot access index {} of JSON null", index),
1278 JsonValue::Bool(_) => panic!("cannot access index {} of JSON boolean", index),
1279 JsonValue::Number(_) => panic!("cannot access index {} of JSON number", index),
1280 JsonValue::String(_) => panic!("cannot access index {} of JSON string", index),
1281 JsonValue::Object(_) => panic!("cannot access index {} of JSON object", index),
1282 }
1283}
1284
1285impl Index<&str> for JsonValue {
1286 type Output = JsonValue;
1287
1288 fn index(&self, index: &str) -> &Self::Output {
1289 match self {
1290 JsonValue::Object(entries) => object_get(entries, index).unwrap_or(&JSON_NULL),
1291 _ => &JSON_NULL,
1292 }
1293 }
1294}
1295
1296impl Index<String> for JsonValue {
1297 type Output = JsonValue;
1298
1299 fn index(&self, index: String) -> &Self::Output {
1300 self.index(index.as_str())
1301 }
1302}
1303
1304impl Index<usize> for JsonValue {
1305 type Output = JsonValue;
1306
1307 fn index(&self, index: usize) -> &Self::Output {
1308 match self {
1309 JsonValue::Array(values) => values.get(index).unwrap_or(&JSON_NULL),
1310 _ => &JSON_NULL,
1311 }
1312 }
1313}
1314
1315impl IndexMut<&str> for JsonValue {
1316 fn index_mut(&mut self, index: &str) -> &mut Self::Output {
1317 object_index_or_insert(self, index)
1318 }
1319}
1320
1321impl IndexMut<String> for JsonValue {
1322 fn index_mut(&mut self, index: String) -> &mut Self::Output {
1323 object_index_or_insert(self, &index)
1324 }
1325}
1326
1327impl IndexMut<usize> for JsonValue {
1328 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1329 array_index_or_panic(self, index)
1330 }
1331}
1332
1333fn eq_i64(value: &JsonValue, other: i64) -> bool {
1334 value.as_i64() == Some(other)
1335}
1336
1337fn eq_u64(value: &JsonValue, other: u64) -> bool {
1338 value.as_u64() == Some(other)
1339}
1340
1341fn eq_f32(value: &JsonValue, other: f32) -> bool {
1342 value.as_f32() == Some(other)
1343}
1344
1345fn eq_f64(value: &JsonValue, other: f64) -> bool {
1346 value.as_f64() == Some(other)
1347}
1348
1349fn eq_bool(value: &JsonValue, other: bool) -> bool {
1350 value.as_bool() == Some(other)
1351}
1352
1353fn eq_str(value: &JsonValue, other: &str) -> bool {
1354 value.as_str() == Some(other)
1355}
1356
1357impl PartialEq<str> for JsonValue {
1358 fn eq(&self, other: &str) -> bool {
1359 eq_str(self, other)
1360 }
1361}
1362
1363impl PartialEq<&str> for JsonValue {
1364 fn eq(&self, other: &&str) -> bool {
1365 eq_str(self, *other)
1366 }
1367}
1368
1369impl PartialEq<JsonValue> for str {
1370 fn eq(&self, other: &JsonValue) -> bool {
1371 eq_str(other, self)
1372 }
1373}
1374
1375impl PartialEq<JsonValue> for &str {
1376 fn eq(&self, other: &JsonValue) -> bool {
1377 eq_str(other, *self)
1378 }
1379}
1380
1381impl PartialEq<String> for JsonValue {
1382 fn eq(&self, other: &String) -> bool {
1383 eq_str(self, other.as_str())
1384 }
1385}
1386
1387impl PartialEq<JsonValue> for String {
1388 fn eq(&self, other: &JsonValue) -> bool {
1389 eq_str(other, self.as_str())
1390 }
1391}
1392
1393macro_rules! partialeq_numeric {
1394 ($($eq:ident [$($ty:ty)*])*) => {
1395 $($(
1396 impl PartialEq<$ty> for JsonValue {
1397 fn eq(&self, other: &$ty) -> bool {
1398 $eq(self, *other as _)
1399 }
1400 }
1401
1402 impl PartialEq<JsonValue> for $ty {
1403 fn eq(&self, other: &JsonValue) -> bool {
1404 $eq(other, *self as _)
1405 }
1406 }
1407
1408 impl<'a> PartialEq<$ty> for &'a JsonValue {
1409 fn eq(&self, other: &$ty) -> bool {
1410 $eq(*self, *other as _)
1411 }
1412 }
1413
1414 impl<'a> PartialEq<$ty> for &'a mut JsonValue {
1415 fn eq(&self, other: &$ty) -> bool {
1416 $eq(*self, *other as _)
1417 }
1418 }
1419 )*)*
1420 }
1421}
1422
1423partialeq_numeric! {
1424 eq_i64[i8 i16 i32 i64 isize]
1425 eq_u64[u8 u16 u32 u64 usize]
1426 eq_f32[f32]
1427 eq_f64[f64]
1428 eq_bool[bool]
1429}
1430
1431#[macro_export]
1432macro_rules! json_unexpected {
1433 ($unexpected:tt) => {
1434 compile_error!(concat!("unexpected token in json! macro: ", stringify!($unexpected)))
1435 };
1436 () => {
1437 compile_error!("unexpected end of json! macro invocation")
1438 };
1439}
1440
1441#[macro_export]
1442macro_rules! json {
1443 ($($json:tt)+) => {
1444 $crate::json_internal!($($json)+)
1445 };
1446}
1447
1448#[macro_export]
1449#[doc(hidden)]
1450macro_rules! json_internal {
1451 (@array [$($elems:expr,)*]) => {
1452 vec![$($elems,)*]
1453 };
1454 (@array [$($elems:expr),*]) => {
1455 vec![$($elems),*]
1456 };
1457 (@array [$($elems:expr,)*] null $($rest:tt)*) => {
1458 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!(null)] $($rest)*)
1459 };
1460 (@array [$($elems:expr,)*] true $($rest:tt)*) => {
1461 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!(true)] $($rest)*)
1462 };
1463 (@array [$($elems:expr,)*] false $($rest:tt)*) => {
1464 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!(false)] $($rest)*)
1465 };
1466 (@array [$($elems:expr,)*] [$($array:tt)*] $($rest:tt)*) => {
1467 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!([$($array)*])] $($rest)*)
1468 };
1469 (@array [$($elems:expr,)*] {$($map:tt)*} $($rest:tt)*) => {
1470 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!({$($map)*})] $($rest)*)
1471 };
1472 (@array [$($elems:expr,)*] $next:expr, $($rest:tt)*) => {
1473 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!($next),] $($rest)*)
1474 };
1475 (@array [$($elems:expr,)*] $last:expr) => {
1476 $crate::json_internal!(@array [$($elems,)* $crate::json_internal!($last)])
1477 };
1478 (@array [$($elems:expr),*] , $($rest:tt)*) => {
1479 $crate::json_internal!(@array [$($elems,)*] $($rest)*)
1480 };
1481 (@array [$($elems:expr),*] $unexpected:tt $($rest:tt)*) => {
1482 $crate::json_unexpected!($unexpected)
1483 };
1484
1485 (@object $object:ident () () ()) => {};
1486 (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => {
1487 $object.push((($($key)+).into(), $value));
1488 $crate::json_internal!(@object $object () ($($rest)*) ($($rest)*));
1489 };
1490 (@object $object:ident [$($key:tt)+] ($value:expr)) => {
1491 $object.push((($($key)+).into(), $value));
1492 };
1493 (@object $object:ident [$($key:tt)+] ($value:expr) $unexpected:tt $($rest:tt)*) => {
1494 $crate::json_unexpected!($unexpected)
1495 };
1496 (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => {
1497 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!(null)) $($rest)*);
1498 };
1499 (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => {
1500 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!(true)) $($rest)*);
1501 };
1502 (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => {
1503 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!(false)) $($rest)*);
1504 };
1505 (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => {
1506 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!([$($array)*])) $($rest)*);
1507 };
1508 (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => {
1509 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!({$($map)*})) $($rest)*);
1510 };
1511 (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => {
1512 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!($value)) , $($rest)*);
1513 };
1514 (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => {
1515 $crate::json_internal!(@object $object [$($key)+] ($crate::json_internal!($value)));
1516 };
1517 (@object $object:ident ($($key:tt)+) (:) $copy:tt) => {
1518 $crate::json_internal!();
1519 };
1520 (@object $object:ident ($($key:tt)+) () $copy:tt) => {
1521 $crate::json_internal!();
1522 };
1523 (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => {
1524 $crate::json_unexpected!($colon)
1525 };
1526 (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => {
1527 $crate::json_unexpected!($comma)
1528 };
1529 (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) ($($copy:tt)*)) => {
1530 $crate::json_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*));
1531 };
1532
1533 (null) => { $crate::JsonValue::Null };
1534 (true) => { $crate::JsonValue::Bool(true) };
1535 (false) => { $crate::JsonValue::Bool(false) };
1536 ([]) => { $crate::JsonValue::Array(vec![]) };
1537 ([ $($tt:tt)+ ]) => { $crate::JsonValue::Array($crate::json_internal!(@array [] $($tt)+)) };
1538 ({}) => { $crate::JsonValue::Object($crate::Map::new()) };
1539 ({ $($tt:tt)+ }) => {{
1540 let mut object = $crate::Map::new();
1541 $crate::json_internal!(@object object () ($($tt)+) ($($tt)+));
1542 $crate::JsonValue::Object(object)
1543 }};
1544 ($other:expr) => { $crate::JsonValue::from($other) };
1545}
1546
1547fn decode_pointer_segment(segment: &str) -> String {
1548 let mut out = String::with_capacity(segment.len());
1549 let bytes = segment.as_bytes();
1550 let mut i = 0;
1551 while i < bytes.len() {
1552 if bytes[i] == b'~' && i + 1 < bytes.len() {
1553 match bytes[i + 1] {
1554 b'0' => {
1555 out.push('~');
1556 i += 2;
1557 continue;
1558 }
1559 b'1' => {
1560 out.push('/');
1561 i += 2;
1562 continue;
1563 }
1564 _ => {}
1565 }
1566 }
1567 out.push(bytes[i] as char);
1568 i += 1;
1569 }
1570 out
1571}
1572
1573fn write_indent(out: &mut Vec<u8>, depth: usize) {
1574 for _ in 0..depth {
1575 out.extend_from_slice(b" ");
1576 }
1577}
1578
1579fn write_json_value_pretty(out: &mut Vec<u8>, value: &JsonValue, depth: usize) -> Result<(), JsonError> {
1580 match value {
1581 JsonValue::Null | JsonValue::Bool(_) | JsonValue::Number(_) | JsonValue::String(_) => {
1582 write_json_value(out, value)
1583 }
1584 JsonValue::Array(values) => {
1585 out.push(b'[');
1586 if !values.is_empty() {
1587 out.push(b'\n');
1588 for (index, value) in values.iter().enumerate() {
1589 if index > 0 {
1590 out.extend_from_slice(b",\n");
1591 }
1592 write_indent(out, depth + 1);
1593 write_json_value_pretty(out, value, depth + 1)?;
1594 }
1595 out.push(b'\n');
1596 write_indent(out, depth);
1597 }
1598 out.push(b']');
1599 Ok(())
1600 }
1601 JsonValue::Object(entries) => {
1602 out.push(b'{');
1603 if !entries.is_empty() {
1604 out.push(b'\n');
1605 for (index, (key, value)) in entries.iter().enumerate() {
1606 if index > 0 {
1607 out.extend_from_slice(b",\n");
1608 }
1609 write_indent(out, depth + 1);
1610 write_json_key(out, key);
1611 out.push(b' ');
1612 write_json_value_pretty(out, value, depth + 1)?;
1613 }
1614 out.push(b'\n');
1615 write_indent(out, depth);
1616 }
1617 out.push(b'}');
1618 Ok(())
1619 }
1620 }
1621}
1622
1623fn hash_key(bytes: &[u8]) -> u64 {
1624 let mut hash = 1469598103934665603u64;
1625 for &byte in bytes {
1626 hash ^= byte as u64;
1627 hash = hash.wrapping_mul(1099511628211u64);
1628 }
1629 hash
1630}
1631
1632#[inline]
1633fn write_json_value(out: &mut Vec<u8>, value: &JsonValue) -> Result<(), JsonError> {
1634 match value {
1635 JsonValue::Null => out.extend_from_slice(b"null"),
1636 JsonValue::Bool(value) => {
1637 if *value {
1638 out.extend_from_slice(b"true");
1639 } else {
1640 out.extend_from_slice(b"false");
1641 }
1642 }
1643 JsonValue::Number(number) => write_json_number(out, number)?,
1644 JsonValue::String(value) => {
1645 write_escaped_json_string(out, value);
1646 }
1647 JsonValue::Array(values) => {
1648 write_json_array(out, values)?;
1649 }
1650 JsonValue::Object(entries) => {
1651 write_json_object(out, entries)?;
1652 }
1653 }
1654 Ok(())
1655}
1656
1657#[inline]
1658fn write_json_number(out: &mut Vec<u8>, value: &JsonNumber) -> Result<(), JsonError> {
1659 match value {
1660 JsonNumber::I64(value) => {
1661 append_i64(out, *value);
1662 Ok(())
1663 }
1664 JsonNumber::U64(value) => {
1665 append_u64(out, *value);
1666 Ok(())
1667 }
1668 JsonNumber::F64(value) => {
1669 if !value.is_finite() {
1670 return Err(JsonError::NonFiniteNumber);
1671 }
1672 out.extend_from_slice(value.to_string().as_bytes());
1673 Ok(())
1674 }
1675 }
1676}
1677
1678#[inline]
1679fn write_escaped_json_string(out: &mut Vec<u8>, input: &str) {
1680 out.push(b'"');
1681 let bytes = input.as_bytes();
1682 let mut fast_index = 0usize;
1683 while fast_index < bytes.len() {
1684 let byte = bytes[fast_index];
1685 if needs_escape(byte) {
1686 break;
1687 }
1688 fast_index += 1;
1689 }
1690 if fast_index == bytes.len() {
1691 out.extend_from_slice(bytes);
1692 out.push(b'"');
1693 return;
1694 }
1695
1696 if fast_index > 0 {
1697 out.extend_from_slice(&bytes[..fast_index]);
1698 }
1699
1700 let mut chunk_start = fast_index;
1701 for (index, byte) in bytes.iter().copied().enumerate().skip(fast_index) {
1702 let escape = match byte {
1703 b'"' => Some(br#"\""#.as_slice()),
1704 b'\\' => Some(br#"\\"#.as_slice()),
1705 0x08 => Some(br#"\b"#.as_slice()),
1706 0x0c => Some(br#"\f"#.as_slice()),
1707 b'\n' => Some(br#"\n"#.as_slice()),
1708 b'\r' => Some(br#"\r"#.as_slice()),
1709 b'\t' => Some(br#"\t"#.as_slice()),
1710 _ => None,
1711 };
1712 if let Some(escape) = escape {
1713 if chunk_start < index {
1714 out.extend_from_slice(&bytes[chunk_start..index]);
1715 }
1716 out.extend_from_slice(escape);
1717 chunk_start = index + 1;
1718 continue;
1719 }
1720 if byte <= 0x1f {
1721 if chunk_start < index {
1722 out.extend_from_slice(&bytes[chunk_start..index]);
1723 }
1724 out.extend_from_slice(br#"\u00"#);
1725 out.push(hex_digit((byte >> 4) & 0x0f));
1726 out.push(hex_digit(byte & 0x0f));
1727 chunk_start = index + 1;
1728 }
1729 }
1730 if chunk_start < input.len() {
1731 out.extend_from_slice(&bytes[chunk_start..]);
1732 }
1733 out.push(b'"');
1734}
1735
1736#[inline]
1737fn needs_escape(byte: u8) -> bool {
1738 matches!(byte, b'"' | b'\\' | 0x00..=0x1f)
1739}
1740
1741#[inline]
1742fn write_json_array(out: &mut Vec<u8>, values: &[JsonValue]) -> Result<(), JsonError> {
1743 out.push(b'[');
1744 match values {
1745 [] => {}
1746 [one] => {
1747 write_json_value(out, one)?;
1748 }
1749 [a, b] => {
1750 write_json_value(out, a)?;
1751 out.push(b',');
1752 write_json_value(out, b)?;
1753 }
1754 [a, b, c] => {
1755 write_json_value(out, a)?;
1756 out.push(b',');
1757 write_json_value(out, b)?;
1758 out.push(b',');
1759 write_json_value(out, c)?;
1760 }
1761 _ => {
1762 let mut iter = values.iter();
1763 if let Some(first) = iter.next() {
1764 write_json_value(out, first)?;
1765 for value in iter {
1766 out.push(b',');
1767 write_json_value(out, value)?;
1768 }
1769 }
1770 }
1771 }
1772 out.push(b']');
1773 Ok(())
1774}
1775
1776#[inline]
1777fn write_json_object(out: &mut Vec<u8>, entries: &[(String, JsonValue)]) -> Result<(), JsonError> {
1778 out.push(b'{');
1779 match entries {
1780 [] => {}
1781 [(k1, v1)] => {
1782 write_json_key(out, k1);
1783 write_json_value(out, v1)?;
1784 }
1785 [(k1, v1), (k2, v2)] => {
1786 write_json_key(out, k1);
1787 write_json_value(out, v1)?;
1788 out.push(b',');
1789 write_json_key(out, k2);
1790 write_json_value(out, v2)?;
1791 }
1792 [(k1, v1), (k2, v2), (k3, v3)] => {
1793 write_json_key(out, k1);
1794 write_json_value(out, v1)?;
1795 out.push(b',');
1796 write_json_key(out, k2);
1797 write_json_value(out, v2)?;
1798 out.push(b',');
1799 write_json_key(out, k3);
1800 write_json_value(out, v3)?;
1801 }
1802 _ => {
1803 let mut iter = entries.iter();
1804 if let Some((first_key, first_value)) = iter.next() {
1805 write_json_key(out, first_key);
1806 write_json_value(out, first_value)?;
1807 for (key, value) in iter {
1808 out.push(b',');
1809 write_json_key(out, key);
1810 write_json_value(out, value)?;
1811 }
1812 }
1813 }
1814 }
1815 out.push(b'}');
1816 Ok(())
1817}
1818
1819#[inline]
1820fn write_json_key(out: &mut Vec<u8>, key: &str) {
1821 let bytes = key.as_bytes();
1822 if is_plain_json_string(bytes) {
1823 out.push(b'"');
1824 out.extend_from_slice(bytes);
1825 out.extend_from_slice(b"\":");
1826 } else {
1827 write_escaped_json_string(out, key);
1828 out.push(b':');
1829 }
1830}
1831
1832#[inline]
1833fn is_plain_json_string(bytes: &[u8]) -> bool {
1834 for &byte in bytes {
1835 if needs_escape(byte) {
1836 return false;
1837 }
1838 }
1839 true
1840}
1841
1842fn initial_json_capacity(value: &JsonValue) -> usize {
1843 match value {
1844 JsonValue::Null => 4,
1845 JsonValue::Bool(true) => 4,
1846 JsonValue::Bool(false) => 5,
1847 JsonValue::Number(JsonNumber::I64(value)) => estimate_i64_len(*value),
1848 JsonValue::Number(JsonNumber::U64(value)) => estimate_u64_len(*value),
1849 JsonValue::Number(JsonNumber::F64(_)) => 24,
1850 JsonValue::String(value) => estimate_escaped_string_len(value),
1851 JsonValue::Array(values) => 2 + values.len().saturating_mul(16),
1852 JsonValue::Object(entries) => {
1853 2 + entries
1854 .iter()
1855 .map(|(key, _)| estimate_escaped_string_len(key) + 8)
1856 .sum::<usize>()
1857 }
1858 }
1859}
1860
1861fn estimate_escaped_string_len(value: &str) -> usize {
1862 let mut len = 2;
1863 for ch in value.chars() {
1864 len += match ch {
1865 '"' | '\\' | '\u{08}' | '\u{0C}' | '\n' | '\r' | '\t' => 2,
1866 ch if ch <= '\u{1F}' => 6,
1867 ch => ch.len_utf8(),
1868 };
1869 }
1870 len
1871}
1872
1873fn estimate_u64_len(mut value: u64) -> usize {
1874 let mut len = 1;
1875 while value >= 10 {
1876 value /= 10;
1877 len += 1;
1878 }
1879 len
1880}
1881
1882fn estimate_i64_len(value: i64) -> usize {
1883 if value < 0 {
1884 1 + estimate_u64_len(value.unsigned_abs())
1885 } else {
1886 estimate_u64_len(value as u64)
1887 }
1888}
1889
1890fn append_i64(out: &mut Vec<u8>, value: i64) {
1891 if value < 0 {
1892 out.push(b'-');
1893 append_u64(out, value.unsigned_abs());
1894 } else {
1895 append_u64(out, value as u64);
1896 }
1897}
1898
1899fn append_u64(out: &mut Vec<u8>, mut value: u64) {
1900 let mut buf = [0u8; 20];
1901 let mut index = buf.len();
1902 loop {
1903 index -= 1;
1904 buf[index] = b'0' + (value % 10) as u8;
1905 value /= 10;
1906 if value == 0 {
1907 break;
1908 }
1909 }
1910 out.extend_from_slice(&buf[index..]);
1911}
1912
1913fn hex_digit(value: u8) -> u8 {
1914 match value {
1915 0..=9 => b'0' + value,
1916 10..=15 => b'a' + (value - 10),
1917 _ => unreachable!(),
1918 }
1919}
1920
1921struct Parser<'a> {
1922 input: &'a str,
1923 bytes: &'a [u8],
1924 index: usize,
1925}
1926
1927impl<'a> Parser<'a> {
1928 fn new(input: &'a str) -> Self {
1929 Self {
1930 input,
1931 bytes: input.as_bytes(),
1932 index: 0,
1933 }
1934 }
1935
1936 fn parse_value(&mut self) -> Result<JsonValue, JsonParseError> {
1937 self.skip_whitespace();
1938 match self.peek_byte() {
1939 Some(b'n') => self.parse_literal(b"null", JsonValue::Null),
1940 Some(b't') => self.parse_literal(b"true", JsonValue::Bool(true)),
1941 Some(b'f') => self.parse_literal(b"false", JsonValue::Bool(false)),
1942 Some(b'"') => Ok(JsonValue::String(self.parse_string()?)),
1943 Some(b'[') => self.parse_array(),
1944 Some(b'{') => self.parse_object(),
1945 Some(b'-' | b'0'..=b'9') => self.parse_number().map(JsonValue::Number),
1946 Some(found) => Err(JsonParseError::UnexpectedCharacter {
1947 index: self.index,
1948 found: found as char,
1949 }),
1950 None => Err(JsonParseError::UnexpectedEnd),
1951 }
1952 }
1953
1954 fn parse_value_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
1955 self.skip_whitespace();
1956 match self.peek_byte() {
1957 Some(b'n') => self.parse_literal_borrowed(b"null", BorrowedJsonValue::Null),
1958 Some(b't') => self.parse_literal_borrowed(b"true", BorrowedJsonValue::Bool(true)),
1959 Some(b'f') => self.parse_literal_borrowed(b"false", BorrowedJsonValue::Bool(false)),
1960 Some(b'"') => Ok(BorrowedJsonValue::String(self.parse_string_borrowed()?)),
1961 Some(b'[') => self.parse_array_borrowed(),
1962 Some(b'{') => self.parse_object_borrowed(),
1963 Some(b'-' | b'0'..=b'9') => self.parse_number().map(BorrowedJsonValue::Number),
1964 Some(found) => Err(JsonParseError::UnexpectedCharacter {
1965 index: self.index,
1966 found: found as char,
1967 }),
1968 None => Err(JsonParseError::UnexpectedEnd),
1969 }
1970 }
1971
1972 fn parse_tape_value(
1973 &mut self,
1974 tokens: &mut Vec<TapeToken>,
1975 parent: Option<usize>,
1976 ) -> Result<usize, JsonParseError> {
1977 self.skip_whitespace();
1978 match self.peek_byte() {
1979 Some(b'n') => self.parse_tape_literal(tokens, parent, b"null", TapeTokenKind::Null),
1980 Some(b't') => self.parse_tape_literal(tokens, parent, b"true", TapeTokenKind::Bool),
1981 Some(b'f') => self.parse_tape_literal(tokens, parent, b"false", TapeTokenKind::Bool),
1982 Some(b'"') => self.parse_tape_string(tokens, parent, TapeTokenKind::String),
1983 Some(b'[') => self.parse_tape_array(tokens, parent),
1984 Some(b'{') => self.parse_tape_object(tokens, parent),
1985 Some(b'-' | b'0'..=b'9') => self.parse_tape_number(tokens, parent),
1986 Some(found) => Err(JsonParseError::UnexpectedCharacter {
1987 index: self.index,
1988 found: found as char,
1989 }),
1990 None => Err(JsonParseError::UnexpectedEnd),
1991 }
1992 }
1993
1994 fn parse_literal(
1995 &mut self,
1996 expected: &[u8],
1997 value: JsonValue,
1998 ) -> Result<JsonValue, JsonParseError> {
1999 if self.bytes[self.index..].starts_with(expected) {
2000 self.index += expected.len();
2001 Ok(value)
2002 } else {
2003 Err(JsonParseError::InvalidLiteral { index: self.index })
2004 }
2005 }
2006
2007 fn parse_literal_borrowed(
2008 &mut self,
2009 expected: &[u8],
2010 value: BorrowedJsonValue<'a>,
2011 ) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
2012 if self.bytes[self.index..].starts_with(expected) {
2013 self.index += expected.len();
2014 Ok(value)
2015 } else {
2016 Err(JsonParseError::InvalidLiteral { index: self.index })
2017 }
2018 }
2019
2020 fn parse_tape_literal(
2021 &mut self,
2022 tokens: &mut Vec<TapeToken>,
2023 parent: Option<usize>,
2024 expected: &[u8],
2025 kind: TapeTokenKind,
2026 ) -> Result<usize, JsonParseError> {
2027 let start = self.index;
2028 if self.bytes[self.index..].starts_with(expected) {
2029 self.index += expected.len();
2030 let token_index = tokens.len();
2031 tokens.push(TapeToken {
2032 kind,
2033 start,
2034 end: self.index,
2035 parent,
2036 });
2037 Ok(token_index)
2038 } else {
2039 Err(JsonParseError::InvalidLiteral { index: self.index })
2040 }
2041 }
2042
2043 fn parse_array(&mut self) -> Result<JsonValue, JsonParseError> {
2044 self.consume_byte(b'[')?;
2045 self.skip_whitespace();
2046 let mut values = Vec::new();
2047 if self.try_consume_byte(b']') {
2048 return Ok(JsonValue::Array(values));
2049 }
2050 loop {
2051 values.push(self.parse_value()?);
2052 self.skip_whitespace();
2053 if self.try_consume_byte(b']') {
2054 break;
2055 }
2056 if !self.try_consume_byte(b',') {
2057 return Err(JsonParseError::ExpectedCommaOrEnd {
2058 index: self.index,
2059 context: "array",
2060 });
2061 }
2062 self.skip_whitespace();
2063 }
2064 Ok(JsonValue::Array(values))
2065 }
2066
2067 fn parse_array_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
2068 self.consume_byte(b'[')?;
2069 self.skip_whitespace();
2070 let mut values = Vec::new();
2071 if self.try_consume_byte(b']') {
2072 return Ok(BorrowedJsonValue::Array(values));
2073 }
2074 loop {
2075 values.push(self.parse_value_borrowed()?);
2076 self.skip_whitespace();
2077 if self.try_consume_byte(b']') {
2078 break;
2079 }
2080 if !self.try_consume_byte(b',') {
2081 return Err(JsonParseError::ExpectedCommaOrEnd {
2082 index: self.index,
2083 context: "array",
2084 });
2085 }
2086 self.skip_whitespace();
2087 }
2088 Ok(BorrowedJsonValue::Array(values))
2089 }
2090
2091 fn parse_tape_array(
2092 &mut self,
2093 tokens: &mut Vec<TapeToken>,
2094 parent: Option<usize>,
2095 ) -> Result<usize, JsonParseError> {
2096 let start = self.index;
2097 self.consume_byte(b'[')?;
2098 let token_index = tokens.len();
2099 tokens.push(TapeToken {
2100 kind: TapeTokenKind::Array,
2101 start,
2102 end: start,
2103 parent,
2104 });
2105 self.skip_whitespace();
2106 if self.try_consume_byte(b']') {
2107 tokens[token_index].end = self.index;
2108 return Ok(token_index);
2109 }
2110 loop {
2111 self.parse_tape_value(tokens, Some(token_index))?;
2112 self.skip_whitespace();
2113 if self.try_consume_byte(b']') {
2114 tokens[token_index].end = self.index;
2115 break;
2116 }
2117 if !self.try_consume_byte(b',') {
2118 return Err(JsonParseError::ExpectedCommaOrEnd {
2119 index: self.index,
2120 context: "array",
2121 });
2122 }
2123 self.skip_whitespace();
2124 }
2125 Ok(token_index)
2126 }
2127
2128 fn parse_object(&mut self) -> Result<JsonValue, JsonParseError> {
2129 self.consume_byte(b'{')?;
2130 self.skip_whitespace();
2131 let mut entries = Map::new();
2132 if self.try_consume_byte(b'}') {
2133 return Ok(JsonValue::Object(entries));
2134 }
2135 loop {
2136 if self.peek_byte() != Some(b'"') {
2137 return match self.peek_byte() {
2138 Some(found) => Err(JsonParseError::UnexpectedCharacter {
2139 index: self.index,
2140 found: found as char,
2141 }),
2142 None => Err(JsonParseError::UnexpectedEnd),
2143 };
2144 }
2145 let key = self.parse_string()?;
2146 self.skip_whitespace();
2147 if !self.try_consume_byte(b':') {
2148 return Err(JsonParseError::ExpectedColon { index: self.index });
2149 }
2150 let value = self.parse_value()?;
2151 entries.push((key, value));
2152 self.skip_whitespace();
2153 if self.try_consume_byte(b'}') {
2154 break;
2155 }
2156 if !self.try_consume_byte(b',') {
2157 return Err(JsonParseError::ExpectedCommaOrEnd {
2158 index: self.index,
2159 context: "object",
2160 });
2161 }
2162 self.skip_whitespace();
2163 }
2164 Ok(JsonValue::Object(entries))
2165 }
2166
2167 fn parse_object_borrowed(&mut self) -> Result<BorrowedJsonValue<'a>, JsonParseError> {
2168 self.consume_byte(b'{')?;
2169 self.skip_whitespace();
2170 let mut entries = Vec::new();
2171 if self.try_consume_byte(b'}') {
2172 return Ok(BorrowedJsonValue::Object(entries));
2173 }
2174 loop {
2175 if self.peek_byte() != Some(b'"') {
2176 return match self.peek_byte() {
2177 Some(found) => Err(JsonParseError::UnexpectedCharacter {
2178 index: self.index,
2179 found: found as char,
2180 }),
2181 None => Err(JsonParseError::UnexpectedEnd),
2182 };
2183 }
2184 let key = self.parse_string_borrowed()?;
2185 self.skip_whitespace();
2186 if !self.try_consume_byte(b':') {
2187 return Err(JsonParseError::ExpectedColon { index: self.index });
2188 }
2189 let value = self.parse_value_borrowed()?;
2190 entries.push((key, value));
2191 self.skip_whitespace();
2192 if self.try_consume_byte(b'}') {
2193 break;
2194 }
2195 if !self.try_consume_byte(b',') {
2196 return Err(JsonParseError::ExpectedCommaOrEnd {
2197 index: self.index,
2198 context: "object",
2199 });
2200 }
2201 self.skip_whitespace();
2202 }
2203 Ok(BorrowedJsonValue::Object(entries))
2204 }
2205
2206 fn parse_tape_object(
2207 &mut self,
2208 tokens: &mut Vec<TapeToken>,
2209 parent: Option<usize>,
2210 ) -> Result<usize, JsonParseError> {
2211 let start = self.index;
2212 self.consume_byte(b'{')?;
2213 let token_index = tokens.len();
2214 tokens.push(TapeToken {
2215 kind: TapeTokenKind::Object,
2216 start,
2217 end: start,
2218 parent,
2219 });
2220 self.skip_whitespace();
2221 if self.try_consume_byte(b'}') {
2222 tokens[token_index].end = self.index;
2223 return Ok(token_index);
2224 }
2225 loop {
2226 if self.peek_byte() != Some(b'"') {
2227 return match self.peek_byte() {
2228 Some(found) => Err(JsonParseError::UnexpectedCharacter {
2229 index: self.index,
2230 found: found as char,
2231 }),
2232 None => Err(JsonParseError::UnexpectedEnd),
2233 };
2234 }
2235 self.parse_tape_string(tokens, Some(token_index), TapeTokenKind::Key)?;
2236 self.skip_whitespace();
2237 if !self.try_consume_byte(b':') {
2238 return Err(JsonParseError::ExpectedColon { index: self.index });
2239 }
2240 self.parse_tape_value(tokens, Some(token_index))?;
2241 self.skip_whitespace();
2242 if self.try_consume_byte(b'}') {
2243 tokens[token_index].end = self.index;
2244 break;
2245 }
2246 if !self.try_consume_byte(b',') {
2247 return Err(JsonParseError::ExpectedCommaOrEnd {
2248 index: self.index,
2249 context: "object",
2250 });
2251 }
2252 self.skip_whitespace();
2253 }
2254 Ok(token_index)
2255 }
2256
2257 fn parse_string(&mut self) -> Result<String, JsonParseError> {
2258 self.consume_byte(b'"')?;
2259 let start = self.index;
2260 loop {
2261 let Some(byte) = self.next_byte() else {
2262 return Err(JsonParseError::UnexpectedEnd);
2263 };
2264 match byte {
2265 b'"' => {
2266 let slice = &self.input[start..self.index - 1];
2267 return Ok(slice.to_owned());
2268 }
2269 b'\\' => {
2270 let mut out = String::with_capacity(self.index - start + 8);
2271 out.push_str(&self.input[start..self.index - 1]);
2272 self.parse_escape_into(&mut out, self.index - 1)?;
2273 return self.parse_string_slow(out);
2274 }
2275 0x00..=0x1f => {
2276 return Err(JsonParseError::UnexpectedCharacter {
2277 index: self.index - 1,
2278 found: byte as char,
2279 })
2280 }
2281 _ => {}
2282 }
2283 }
2284 }
2285
2286 fn parse_string_borrowed(&mut self) -> Result<Cow<'a, str>, JsonParseError> {
2287 self.consume_byte(b'"')?;
2288 let start = self.index;
2289 loop {
2290 let Some(byte) = self.next_byte() else {
2291 return Err(JsonParseError::UnexpectedEnd);
2292 };
2293 match byte {
2294 b'"' => {
2295 let slice = &self.input[start..self.index - 1];
2296 return Ok(Cow::Borrowed(slice));
2297 }
2298 b'\\' => {
2299 let mut out = String::with_capacity(self.index - start + 8);
2300 out.push_str(&self.input[start..self.index - 1]);
2301 self.parse_escape_into(&mut out, self.index - 1)?;
2302 return self.parse_string_slow_borrowed(out);
2303 }
2304 0x00..=0x1f => {
2305 return Err(JsonParseError::UnexpectedCharacter {
2306 index: self.index - 1,
2307 found: byte as char,
2308 })
2309 }
2310 _ => {}
2311 }
2312 }
2313 }
2314
2315 fn parse_tape_string(
2316 &mut self,
2317 tokens: &mut Vec<TapeToken>,
2318 parent: Option<usize>,
2319 kind: TapeTokenKind,
2320 ) -> Result<usize, JsonParseError> {
2321 let start = self.index;
2322 self.skip_string_bytes()?;
2323 let token_index = tokens.len();
2324 tokens.push(TapeToken {
2325 kind,
2326 start,
2327 end: self.index,
2328 parent,
2329 });
2330 Ok(token_index)
2331 }
2332
2333 fn skip_string_bytes(&mut self) -> Result<(), JsonParseError> {
2334 self.consume_byte(b'"')?;
2335 loop {
2336 let Some(byte) = self.next_byte() else {
2337 return Err(JsonParseError::UnexpectedEnd);
2338 };
2339 match byte {
2340 b'"' => return Ok(()),
2341 b'\\' => {
2342 let escape_index = self.index - 1;
2343 let escaped = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2344 match escaped {
2345 b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {}
2346 b'u' => {
2347 let scalar = self.parse_hex_quad(escape_index)?;
2348 if (0xD800..=0xDBFF).contains(&scalar) {
2349 if self.next_byte() != Some(b'\\') || self.next_byte() != Some(b'u')
2350 {
2351 return Err(JsonParseError::InvalidUnicodeScalar {
2352 index: escape_index,
2353 });
2354 }
2355 let low = self.parse_hex_quad(escape_index)?;
2356 if !(0xDC00..=0xDFFF).contains(&low) {
2357 return Err(JsonParseError::InvalidUnicodeScalar {
2358 index: escape_index,
2359 });
2360 }
2361 } else if (0xDC00..=0xDFFF).contains(&scalar) {
2362 return Err(JsonParseError::InvalidUnicodeScalar {
2363 index: escape_index,
2364 });
2365 }
2366 }
2367 _ => {
2368 return Err(JsonParseError::InvalidEscape {
2369 index: escape_index,
2370 })
2371 }
2372 }
2373 }
2374 0x00..=0x1f => {
2375 return Err(JsonParseError::UnexpectedCharacter {
2376 index: self.index - 1,
2377 found: byte as char,
2378 })
2379 }
2380 _ => {}
2381 }
2382 }
2383 }
2384
2385 fn parse_string_slow(&mut self, mut out: String) -> Result<String, JsonParseError> {
2386 let mut chunk_start = self.index;
2387 loop {
2388 let Some(byte) = self.next_byte() else {
2389 return Err(JsonParseError::UnexpectedEnd);
2390 };
2391 match byte {
2392 b'"' => {
2393 if chunk_start < self.index - 1 {
2394 out.push_str(&self.input[chunk_start..self.index - 1]);
2395 }
2396 return Ok(out);
2397 }
2398 b'\\' => {
2399 if chunk_start < self.index - 1 {
2400 out.push_str(&self.input[chunk_start..self.index - 1]);
2401 }
2402 self.parse_escape_into(&mut out, self.index - 1)?;
2403 chunk_start = self.index;
2404 }
2405 0x00..=0x1f => {
2406 return Err(JsonParseError::UnexpectedCharacter {
2407 index: self.index - 1,
2408 found: byte as char,
2409 })
2410 }
2411 _ => {}
2412 }
2413 }
2414 }
2415
2416 fn parse_string_slow_borrowed(
2417 &mut self,
2418 mut out: String,
2419 ) -> Result<Cow<'a, str>, JsonParseError> {
2420 let mut chunk_start = self.index;
2421 loop {
2422 let Some(byte) = self.next_byte() else {
2423 return Err(JsonParseError::UnexpectedEnd);
2424 };
2425 match byte {
2426 b'"' => {
2427 if chunk_start < self.index - 1 {
2428 out.push_str(&self.input[chunk_start..self.index - 1]);
2429 }
2430 return Ok(Cow::Owned(out));
2431 }
2432 b'\\' => {
2433 if chunk_start < self.index - 1 {
2434 out.push_str(&self.input[chunk_start..self.index - 1]);
2435 }
2436 self.parse_escape_into(&mut out, self.index - 1)?;
2437 chunk_start = self.index;
2438 }
2439 0x00..=0x1f => {
2440 return Err(JsonParseError::UnexpectedCharacter {
2441 index: self.index - 1,
2442 found: byte as char,
2443 })
2444 }
2445 _ => {}
2446 }
2447 }
2448 }
2449
2450 fn parse_escape_into(
2451 &mut self,
2452 out: &mut String,
2453 escape_index: usize,
2454 ) -> Result<(), JsonParseError> {
2455 let escaped = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2456 match escaped {
2457 b'"' => out.push('"'),
2458 b'\\' => out.push('\\'),
2459 b'/' => out.push('/'),
2460 b'b' => out.push('\u{0008}'),
2461 b'f' => out.push('\u{000C}'),
2462 b'n' => out.push('\n'),
2463 b'r' => out.push('\r'),
2464 b't' => out.push('\t'),
2465 b'u' => out.push(self.parse_unicode_escape(escape_index)?),
2466 _ => {
2467 return Err(JsonParseError::InvalidEscape {
2468 index: escape_index,
2469 })
2470 }
2471 }
2472 Ok(())
2473 }
2474
2475 fn parse_unicode_escape(&mut self, index: usize) -> Result<char, JsonParseError> {
2476 let scalar = self.parse_hex_quad(index)?;
2477 if (0xD800..=0xDBFF).contains(&scalar) {
2478 if self.next_byte() != Some(b'\\') || self.next_byte() != Some(b'u') {
2479 return Err(JsonParseError::InvalidUnicodeScalar { index });
2480 }
2481 let low = self.parse_hex_quad(index)?;
2482 if !(0xDC00..=0xDFFF).contains(&low) {
2483 return Err(JsonParseError::InvalidUnicodeScalar { index });
2484 }
2485 let high = scalar - 0xD800;
2486 let low = low - 0xDC00;
2487 let combined = 0x10000 + ((high << 10) | low);
2488 char::from_u32(combined).ok_or(JsonParseError::InvalidUnicodeScalar { index })
2489 } else if (0xDC00..=0xDFFF).contains(&scalar) {
2490 Err(JsonParseError::InvalidUnicodeScalar { index })
2491 } else {
2492 char::from_u32(scalar).ok_or(JsonParseError::InvalidUnicodeScalar { index })
2493 }
2494 }
2495
2496 fn parse_hex_quad(&mut self, index: usize) -> Result<u32, JsonParseError> {
2497 let mut value = 0u32;
2498 for _ in 0..4 {
2499 let ch = self.next_byte().ok_or(JsonParseError::UnexpectedEnd)?;
2500 let digit = match ch {
2501 b'0'..=b'9' => (ch - b'0') as u32,
2502 b'a'..=b'f' => 10 + (ch - b'a') as u32,
2503 b'A'..=b'F' => 10 + (ch - b'A') as u32,
2504 _ => return Err(JsonParseError::InvalidUnicodeEscape { index }),
2505 };
2506 value = (value << 4) | digit;
2507 }
2508 Ok(value)
2509 }
2510
2511 fn parse_number(&mut self) -> Result<JsonNumber, JsonParseError> {
2512 let start = self.index;
2513 self.try_consume_byte(b'-');
2514 if self.try_consume_byte(b'0') {
2515 if matches!(self.peek_byte(), Some(b'0'..=b'9')) {
2516 return Err(JsonParseError::InvalidNumber { index: start });
2517 }
2518 } else {
2519 self.consume_digits(start)?;
2520 }
2521
2522 let mut is_float = false;
2523 if self.try_consume_byte(b'.') {
2524 is_float = true;
2525 self.consume_digits(start)?;
2526 }
2527 if matches!(self.peek_byte(), Some(b'e' | b'E')) {
2528 is_float = true;
2529 self.index += 1;
2530 if matches!(self.peek_byte(), Some(b'+' | b'-')) {
2531 self.index += 1;
2532 }
2533 self.consume_digits(start)?;
2534 }
2535
2536 let token = &self.input[start..self.index];
2537 if is_float {
2538 let value = token
2539 .parse::<f64>()
2540 .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2541 if !value.is_finite() {
2542 return Err(JsonParseError::InvalidNumber { index: start });
2543 }
2544 Ok(JsonNumber::F64(value))
2545 } else if token.starts_with('-') {
2546 let value = token
2547 .parse::<i64>()
2548 .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2549 Ok(JsonNumber::I64(value))
2550 } else {
2551 let value = token
2552 .parse::<u64>()
2553 .map_err(|_| JsonParseError::InvalidNumber { index: start })?;
2554 Ok(JsonNumber::U64(value))
2555 }
2556 }
2557
2558 fn parse_tape_number(
2559 &mut self,
2560 tokens: &mut Vec<TapeToken>,
2561 parent: Option<usize>,
2562 ) -> Result<usize, JsonParseError> {
2563 let start = self.index;
2564 let _ = self.parse_number()?;
2565 let token_index = tokens.len();
2566 tokens.push(TapeToken {
2567 kind: TapeTokenKind::Number,
2568 start,
2569 end: self.index,
2570 parent,
2571 });
2572 Ok(token_index)
2573 }
2574
2575 fn consume_digits(&mut self, index: usize) -> Result<(), JsonParseError> {
2576 let start = self.index;
2577 while matches!(self.peek_byte(), Some(b'0'..=b'9')) {
2578 self.index += 1;
2579 }
2580 if self.index == start {
2581 return Err(JsonParseError::InvalidNumber { index });
2582 }
2583 Ok(())
2584 }
2585
2586 fn consume_byte(&mut self, expected: u8) -> Result<(), JsonParseError> {
2587 match self.next_byte() {
2588 Some(found) if found == expected => Ok(()),
2589 Some(found) => Err(JsonParseError::UnexpectedCharacter {
2590 index: self.index.saturating_sub(1),
2591 found: found as char,
2592 }),
2593 None => Err(JsonParseError::UnexpectedEnd),
2594 }
2595 }
2596
2597 fn try_consume_byte(&mut self, expected: u8) -> bool {
2598 if self.peek_byte() == Some(expected) {
2599 self.index += 1;
2600 true
2601 } else {
2602 false
2603 }
2604 }
2605
2606 fn skip_whitespace(&mut self) {
2607 while matches!(self.peek_byte(), Some(b' ' | b'\n' | b'\r' | b'\t')) {
2608 self.index += 1;
2609 }
2610 }
2611
2612 fn peek_byte(&self) -> Option<u8> {
2613 self.bytes.get(self.index).copied()
2614 }
2615
2616 fn next_byte(&mut self) -> Option<u8> {
2617 let byte = self.peek_byte()?;
2618 self.index += 1;
2619 Some(byte)
2620 }
2621
2622 fn is_eof(&self) -> bool {
2623 self.index >= self.input.len()
2624 }
2625}
2626
2627#[cfg(test)]
2628mod tests {
2629 use super::*;
2630
2631 #[test]
2632 fn escapes_control_characters_and_quotes() {
2633 let escaped = escape_json_string("hello\t\"world\"\n\u{0007}");
2634 assert_eq!(escaped, "\"hello\\t\\\"world\\\"\\n\\u0007\"");
2635 }
2636
2637 #[test]
2638 fn serializes_nested_values() {
2639 let value = JsonValue::object(vec![
2640 ("name", "node-1".into()),
2641 ("ok", true.into()),
2642 (
2643 "values",
2644 JsonValue::array(vec![1u32.into(), 2u32.into(), JsonValue::Null]),
2645 ),
2646 ]);
2647 assert_eq!(
2648 value.to_json_string().unwrap(),
2649 "{\"name\":\"node-1\",\"ok\":true,\"values\":[1,2,null]}"
2650 );
2651 }
2652
2653 #[test]
2654 fn rejects_non_finite_float() {
2655 let value = JsonValue::from(f64::NAN);
2656 assert_eq!(value.to_json_string(), Err(JsonError::NonFiniteNumber));
2657 }
2658
2659 #[test]
2660 fn parses_basic_json_values() {
2661 assert_eq!(parse_json("null").unwrap(), JsonValue::Null);
2662 assert_eq!(parse_json("true").unwrap(), JsonValue::Bool(true));
2663 assert_eq!(
2664 parse_json("\"hello\"").unwrap(),
2665 JsonValue::String("hello".into())
2666 );
2667 assert_eq!(
2668 parse_json("123").unwrap(),
2669 JsonValue::Number(JsonNumber::U64(123))
2670 );
2671 assert_eq!(
2672 parse_json("-123").unwrap(),
2673 JsonValue::Number(JsonNumber::I64(-123))
2674 );
2675 }
2676
2677 #[test]
2678 fn parses_unicode_and_escapes() {
2679 let value = parse_json("\"line\\n\\u03bb\\uD83D\\uDE80\"").unwrap();
2680 assert_eq!(value, JsonValue::String("line\nλ🚀".into()));
2681 }
2682
2683 #[test]
2684 fn borrowed_parse_avoids_allocating_plain_strings() {
2685 let value = parse_json_borrowed("{\"name\":\"hello\",\"n\":1}").unwrap();
2686 match value {
2687 BorrowedJsonValue::Object(entries) => {
2688 assert!(matches!(entries[0].0, Cow::Borrowed(_)));
2689 assert!(matches!(
2690 entries[0].1,
2691 BorrowedJsonValue::String(Cow::Borrowed(_))
2692 ));
2693 }
2694 other => panic!("unexpected value: {other:?}"),
2695 }
2696 }
2697
2698 #[test]
2699 fn borrowed_parse_allocates_when_unescaping_is_needed() {
2700 let value = parse_json_borrowed("\"line\\nvalue\"").unwrap();
2701 match value {
2702 BorrowedJsonValue::String(Cow::Owned(text)) => assert_eq!(text, "line\nvalue"),
2703 other => panic!("unexpected value: {other:?}"),
2704 }
2705 }
2706
2707 #[test]
2708 fn compiled_schema_serializes_expected_shape() {
2709 let schema = CompiledObjectSchema::new(&["id", "name", "enabled"]);
2710 let values = [
2711 JsonValue::from(7u64),
2712 JsonValue::from("node-7"),
2713 JsonValue::from(true),
2714 ];
2715 let json = schema.to_json_string(values.iter()).unwrap();
2716 assert_eq!(json, "{\"id\":7,\"name\":\"node-7\",\"enabled\":true}");
2717 }
2718
2719 #[test]
2720 fn compiled_row_schema_serializes_array_of_objects() {
2721 let schema = CompiledRowSchema::new(&["id", "name"]);
2722 let row1 = [JsonValue::from(1u64), JsonValue::from("a")];
2723 let row2 = [JsonValue::from(2u64), JsonValue::from("b")];
2724 let json = schema.to_json_string([row1.iter(), row2.iter()]).unwrap();
2725 assert_eq!(json, r#"[{"id":1,"name":"a"},{"id":2,"name":"b"}]"#);
2726 }
2727
2728 #[test]
2729 fn tape_parse_records_structure_tokens() {
2730 let tape = parse_json_tape(r#"{"a":[1,"x"],"b":true}"#).unwrap();
2731 assert_eq!(tape.tokens[0].kind, TapeTokenKind::Object);
2732 assert_eq!(tape.tokens[1].kind, TapeTokenKind::Key);
2733 assert_eq!(tape.tokens[2].kind, TapeTokenKind::Array);
2734 assert_eq!(tape.tokens[3].kind, TapeTokenKind::Number);
2735 assert_eq!(tape.tokens[4].kind, TapeTokenKind::String);
2736 assert_eq!(tape.tokens[5].kind, TapeTokenKind::Key);
2737 assert_eq!(tape.tokens[6].kind, TapeTokenKind::Bool);
2738 }
2739
2740 #[test]
2741 fn tape_object_lookup_finds_child_values() {
2742 let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2743 let tape = parse_json_tape(input).unwrap();
2744 let root = tape.root(input).unwrap();
2745 let name = root.get("name").unwrap();
2746 assert_eq!(name.kind(), TapeTokenKind::String);
2747 assert_eq!(name.as_str(), Some("hello"));
2748 let nested = root.get("nested").unwrap();
2749 assert_eq!(nested.kind(), TapeTokenKind::Object);
2750 assert!(root.get("missing").is_none());
2751 }
2752
2753 #[test]
2754 fn tape_object_index_lookup_finds_child_values() {
2755 let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2756 let tape = parse_json_tape(input).unwrap();
2757 let root = tape.root(input).unwrap();
2758 let index = root.build_object_index().unwrap();
2759 let flag = index.get(root, "flag").unwrap();
2760 assert_eq!(flag.kind(), TapeTokenKind::Bool);
2761 assert!(index.get(root, "missing").is_none());
2762 }
2763
2764 #[test]
2765 fn indexed_tape_object_compiled_lookup_finds_child_values() {
2766 let input = r#"{"name":"hello","nested":{"x":1},"flag":true}"#;
2767 let tape = parse_json_tape(input).unwrap();
2768 let root = tape.root(input).unwrap();
2769 let index = root.build_object_index().unwrap();
2770 let indexed = root.with_index(&index);
2771 let keys = CompiledTapeKeys::new(&["name", "flag", "missing"]);
2772 let got = indexed
2773 .get_compiled_many(&keys)
2774 .map(|value| value.map(|value| value.kind()))
2775 .collect::<Vec<_>>();
2776 assert_eq!(got, vec![Some(TapeTokenKind::String), Some(TapeTokenKind::Bool), None]);
2777 }
2778
2779 #[test]
2780 fn serde_style_convenience_api_works() {
2781 let value = from_str(r#"{"ok":true,"n":7,"items":[1,2,3],"msg":"hello"}"#).unwrap();
2782 assert!(value.is_object());
2783 assert_eq!(value["ok"].as_bool(), Some(true));
2784 assert_eq!(value["n"].as_i64(), Some(7));
2785 assert_eq!(value["msg"].as_str(), Some("hello"));
2786 assert_eq!(value["items"][1].as_u64(), Some(2));
2787 assert!(value["missing"].is_null());
2788 assert_eq!(to_string(&value).unwrap(), r#"{"ok":true,"n":7,"items":[1,2,3],"msg":"hello"}"#);
2789 assert_eq!(from_slice(br#"[1,true,"x"]"#).unwrap()[2].as_str(), Some("x"));
2790 assert_eq!(to_vec(&value).unwrap(), value.to_json_string().unwrap().into_bytes());
2791 }
2792
2793 #[test]
2794 fn json_macro_builds_values() {
2795 let value = json!({"ok": true, "items": [1, 2, null], "msg": "x"});
2796 assert_eq!(value["ok"].as_bool(), Some(true));
2797 assert_eq!(value["items"][0].as_u64(), Some(1));
2798 assert!(value["items"][2].is_null());
2799 assert_eq!(value["msg"].as_str(), Some("x"));
2800 }
2801
2802 #[test]
2803 fn from_slice_rejects_invalid_utf8() {
2804 assert!(matches!(from_slice(&[0xff]), Err(JsonParseError::InvalidUtf8)));
2805 }
2806
2807 #[test]
2808 fn pointer_take_and_pretty_helpers_work() {
2809 let mut value = from_str(r#"{"a":{"b":[10,20,{"~key/":"x"}]}}"#).unwrap();
2810 assert_eq!(value.pointer("/a/b/1").and_then(JsonValue::as_u64), Some(20));
2811 assert_eq!(value.pointer("/a/b/2/~0key~1").and_then(JsonValue::as_str), Some("x"));
2812 *value.pointer_mut("/a/b/0").unwrap() = JsonValue::from(99u64);
2813 assert_eq!(value.pointer("/a/b/0").and_then(JsonValue::as_u64), Some(99));
2814
2815 let taken = value.pointer_mut("/a/b/2").unwrap().take();
2816 assert!(value.pointer("/a/b/2").unwrap().is_null());
2817 assert_eq!(taken["~key/"].as_str(), Some("x"));
2818
2819 let pretty = to_string_pretty(&value).unwrap();
2820 assert!(pretty.contains("\"a\": {"));
2821 let mut out = Vec::new();
2822 to_writer_pretty(&mut out, &value).unwrap();
2823 assert_eq!(String::from_utf8(out).unwrap(), pretty);
2824 }
2825
2826 #[test]
2827 fn reader_writer_and_collection_helpers_work() {
2828 let value = from_reader(std::io::Cursor::new(br#"{"a":1,"b":[true,false]}"# as &[u8])).unwrap();
2829 assert_eq!(value["a"].as_u64(), Some(1));
2830 assert_eq!(value["b"].len(), 2);
2831 assert_eq!(value["b"].get_index(1).and_then(JsonValue::as_bool), Some(false));
2832
2833 let mut out = Vec::new();
2834 to_writer(&mut out, &value).unwrap();
2835 assert_eq!(String::from_utf8(out).unwrap(), value.to_json_string().unwrap());
2836
2837 let object = JsonValue::from_iter([("x", 1u64), ("y", 2u64)]);
2838 assert_eq!(object["x"].as_u64(), Some(1));
2839 let array = JsonValue::from_iter([1u64, 2u64, 3u64]);
2840 assert_eq!(array.get_index(2).and_then(JsonValue::as_u64), Some(3));
2841 }
2842
2843 #[test]
2844 fn positive_signed_integer_construction_matches_serde_style() {
2845 let value = JsonValue::from(64i64);
2846 assert!(value.is_i64());
2847 assert!(value.is_u64());
2848 assert_eq!(value.as_i64(), Some(64));
2849 assert_eq!(value.as_u64(), Some(64));
2850 assert_eq!(value.as_number(), Some(&JsonNumber::from(64i64)));
2851 }
2852
2853 #[test]
2854 fn json_number_parity_helpers_work() {
2855 let n = JsonNumber::from_i128(42).unwrap();
2856 assert!(n.is_i64() || n.is_u64());
2857 assert_eq!(n.as_i128(), Some(42));
2858 assert_eq!(n.as_u128(), Some(42));
2859 assert_eq!(n.to_string(), "42");
2860
2861 let big = JsonNumber::from_u128(u64::MAX as u128 + 1);
2862 assert!(big.is_none());
2863 assert!(JsonNumber::from_f64(f64::NAN).is_none());
2864 }
2865
2866 #[test]
2867 fn json_macro_expr_key_parity_works() {
2868 let code = 200;
2869 let features = vec!["serde", "json"];
2870 let value = json!({
2871 "code": code,
2872 "success": code == 200,
2873 features[0]: features[1],
2874 });
2875 assert_eq!(value["code"], 200);
2876 assert_eq!(value["success"], true);
2877 assert_eq!(value["serde"], "json");
2878 }
2879
2880#[test]
2881 fn primitive_partial_eq_parity_works() {
2882 let value = json!({"n": 1, "f": 2.5, "b": true, "s": "x"});
2883 assert_eq!(value["n"], 1);
2884 assert_eq!(1, value["n"]);
2885 assert_eq!(value["f"], 2.5);
2886 assert_eq!(value["b"], true);
2887 assert_eq!(value["s"], "x");
2888 assert_eq!(String::from("x"), value["s"]);
2889 }
2890
2891 #[test]
2892 fn signature_and_sort_parity_helpers_work() {
2893 let mut value = json!({"z": {"b": 2, "a": 1}, "a": [{"d": 4, "c": 3}]});
2894 assert_eq!(value.as_object().unwrap().len(), 2);
2895 assert_eq!(value["a"].as_array().unwrap().len(), 1);
2896 value.sort_all_objects();
2897 let root_keys = value.as_object().unwrap().iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>();
2898 assert_eq!(root_keys, vec!["a", "z"]);
2899 let nested_keys = value["z"].as_object().unwrap().iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>();
2900 assert_eq!(nested_keys, vec!["a", "b"]);
2901 }
2902
2903 #[test]
2904 fn generic_get_and_get_mut_index_parity_work() {
2905 let mut value = json!({"obj": {"x": 1}, "arr": [10, 20, 30]});
2906 let key = String::from("obj");
2907 assert_eq!(value.get("obj").and_then(|v| v.get("x")).and_then(JsonValue::as_u64), Some(1));
2908 assert_eq!(value.get(&key).and_then(|v| v.get("x")).and_then(JsonValue::as_u64), Some(1));
2909 assert_eq!(value.get("arr").and_then(|v| v.get(1)).and_then(JsonValue::as_u64), Some(20));
2910 *value.get_mut("arr").unwrap().get_mut(2).unwrap() = JsonValue::from(99u64);
2911 assert_eq!(value["arr"][2].as_u64(), Some(99));
2912 }
2913
2914 #[test]
2915 fn number_and_mut_index_parity_helpers_work() {
2916 let int = JsonValue::from(7i64);
2917 assert!(int.is_i64());
2918 assert!(int.is_u64());
2919 assert!(!int.is_f64());
2920 assert_eq!(int.as_number().and_then(JsonNumber::as_i64), Some(7));
2921
2922 let float = JsonValue::Number(JsonNumber::from_f64(2.5).unwrap());
2923 assert!(float.is_f64());
2924 assert_eq!(float.as_f64(), Some(2.5));
2925 assert_eq!(JsonValue::Null.as_null(), Some(()));
2926
2927 let mut value = JsonValue::Null;
2928 value["a"]["b"]["c"] = JsonValue::from(true);
2929 assert_eq!(value.pointer("/a/b/c").and_then(JsonValue::as_bool), Some(true));
2930
2931 value["arr"] = json!([1, 2, 3]);
2932 value["arr"][1] = JsonValue::from(9u64);
2933 assert_eq!(value.pointer("/arr/1").and_then(JsonValue::as_u64), Some(9));
2934 }
2935
2936 #[test]
2937 fn serde_map_style_tests_work() {
2938 let v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap();
2939 let keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect();
2940 assert_eq!(keys, vec!["b", "a", "c"]);
2941
2942 let mut v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap();
2943 let val = v.as_object_mut().unwrap();
2944 let mut m = Map::new();
2945 m.append(val);
2946 let keys: Vec<_> = m.keys().cloned().collect();
2947 assert_eq!(keys, vec!["b", "a", "c"]);
2948 assert!(val.is_empty());
2949
2950 let mut v: Value = from_str(r#"{"b":null,"a":null,"c":null}"#).unwrap();
2951 let val = v.as_object_mut().unwrap();
2952 val.retain(|(k, _)| k.as_str() != "b");
2953 let keys: Vec<_> = val.keys().cloned().collect();
2954 assert_eq!(keys, vec!["a", "c"]);
2955 }
2956
2957 #[test]
2958 fn serde_value_doc_examples_get_and_index_work() {
2959 let object = json!({"A": 65, "B": 66, "C": 67});
2960 assert_eq!(*object.get("A").unwrap(), json!(65));
2961
2962 let array = json!(["A", "B", "C"]);
2963 assert_eq!(*array.get(2).unwrap(), json!("C"));
2964 assert_eq!(array.get("A"), None);
2965
2966 let object = json!({"A": ["a", "á", "à"], "B": ["b", "b́"], "C": ["c", "ć", "ć̣", "ḉ"]});
2967 assert_eq!(object["B"][0], json!("b"));
2968 assert_eq!(object["D"], json!(null));
2969 assert_eq!(object[0]["x"]["y"]["z"], json!(null));
2970 }
2971
2972 #[test]
2973 fn serde_value_doc_examples_type_queries_work() {
2974 let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] });
2975 assert!(obj.is_object());
2976 assert!(obj["a"].is_object());
2977 assert!(!obj["b"].is_object());
2978 assert!(obj["b"].is_array());
2979 assert!(!obj["a"].is_array());
2980
2981 let v = json!({ "a": "some string", "b": false });
2982 assert!(v["a"].is_string());
2983 assert!(!v["b"].is_string());
2984
2985 let v = json!({ "a": 1, "b": "2" });
2986 assert!(v["a"].is_number());
2987 assert!(!v["b"].is_number());
2988
2989 let v = json!({ "a": false, "b": "false" });
2990 assert!(v["a"].is_boolean());
2991 assert!(!v["b"].is_boolean());
2992
2993 let v = json!({ "a": null, "b": false });
2994 assert!(v["a"].is_null());
2995 assert!(!v["b"].is_null());
2996 }
2997
2998 #[test]
2999 fn serde_value_doc_examples_accessors_work() {
3000 let v = json!({ "a": { "nested": true }, "b": ["an", "array"] });
3001 assert_eq!(v["a"].as_object().unwrap().len(), 1);
3002 assert_eq!(v["b"].as_array().unwrap().len(), 2);
3003 assert_eq!(v["b"].as_object(), None);
3004
3005 let v = json!({ "a": "some string", "b": false });
3006 assert_eq!(v["a"].as_str(), Some("some string"));
3007 assert_eq!(v["b"].as_str(), None);
3008
3009 let v = json!({ "a": 1, "b": 2.2, "c": -3, "d": "4" });
3010 assert_eq!(v["a"].as_number(), Some(&JsonNumber::from(1u64)));
3011 assert_eq!(v["b"].as_number(), Some(&JsonNumber::from_f64(2.2).unwrap()));
3012 assert_eq!(v["c"].as_number(), Some(&JsonNumber::from(-3i64)));
3013 assert_eq!(v["d"].as_number(), None);
3014 }
3015
3016 #[test]
3017 fn serde_value_doc_examples_numeric_queries_work() {
3018 let big = i64::MAX as u64 + 10;
3019 let v = json!({ "a": 64, "b": big, "c": 256.0 });
3020 assert!(v["a"].is_i64());
3021 assert!(!v["b"].is_i64());
3022 assert!(!v["c"].is_i64());
3023 assert_eq!(v["a"].as_i64(), Some(64));
3024 assert_eq!(v["b"].as_i64(), None);
3025 assert_eq!(v["c"].as_i64(), None);
3026
3027 let v = json!({ "a": 64, "b": -64, "c": 256.0 });
3028 assert!(v["a"].is_u64());
3029 assert!(!v["b"].is_u64());
3030 assert!(!v["c"].is_u64());
3031 assert_eq!(v["a"].as_u64(), Some(64));
3032 assert_eq!(v["b"].as_u64(), None);
3033 assert_eq!(v["c"].as_u64(), None);
3034
3035 let v = json!({ "a": 256.0, "b": 64, "c": -64 });
3036 assert!(v["a"].is_f64());
3037 assert!(!v["b"].is_f64());
3038 assert!(!v["c"].is_f64());
3039 assert_eq!(v["a"].as_f64(), Some(256.0));
3040 assert_eq!(v["b"].as_f64(), Some(64.0));
3041 assert_eq!(v["c"].as_f64(), Some(-64.0));
3042 }
3043
3044 #[test]
3045 fn serde_value_doc_examples_pointer_and_take_work() {
3046 let data = json!({
3047 "x": {
3048 "y": ["z", "zz"]
3049 }
3050 });
3051 assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz"));
3052 assert_eq!(data.pointer("/a/b/c"), None);
3053
3054 let mut value = json!({"x": 1.0, "y": 2.0});
3055 assert_eq!(value.pointer("/x"), Some(&JsonValue::from(1.0)));
3056 if let Some(v) = value.pointer_mut("/x") {
3057 *v = 1.5.into();
3058 }
3059 assert_eq!(value.pointer("/x"), Some(&JsonValue::from(1.5)));
3060 let old_x = value.pointer_mut("/x").map(JsonValue::take).unwrap();
3061 assert_eq!(old_x, JsonValue::from(1.5));
3062 assert_eq!(value.pointer("/x").unwrap(), &JsonValue::Null);
3063
3064 let mut v = json!({"x": "y"});
3065 assert_eq!(v["x"].take(), json!("y"));
3066 assert_eq!(v, json!({"x": null}));
3067 }
3068
3069 #[test]
3070 fn serde_number_doc_examples_work() {
3071 assert!(JsonNumber::from_f64(256.0).is_some());
3072 assert!(JsonNumber::from_f64(f64::NAN).is_none());
3073 assert!(JsonNumber::from_i128(256).is_some());
3074 assert!(JsonNumber::from_u128(256).is_some());
3075 }
3076
3077 #[test]
3078 fn rejects_invalid_json_inputs() {
3079 assert!(matches!(
3080 parse_json("{"),
3081 Err(JsonParseError::UnexpectedEnd)
3082 ));
3083 assert!(matches!(
3084 parse_json("{\"a\" 1}"),
3085 Err(JsonParseError::ExpectedColon { .. })
3086 ));
3087 assert!(matches!(
3088 parse_json("[1 2]"),
3089 Err(JsonParseError::ExpectedCommaOrEnd {
3090 context: "array",
3091 ..
3092 })
3093 ));
3094 assert!(matches!(
3095 parse_json("{\"a\":1 trailing"),
3096 Err(JsonParseError::ExpectedCommaOrEnd {
3097 context: "object",
3098 ..
3099 })
3100 ));
3101 assert!(matches!(
3102 parse_json("00"),
3103 Err(JsonParseError::InvalidNumber { .. })
3104 ));
3105 }
3106
3107 #[test]
3108 fn roundtrips_specific_structures() {
3109 let values = [
3110 JsonValue::Null,
3111 JsonValue::Bool(false),
3112 JsonValue::String("tab\tquote\"slash\\snowman☃".into()),
3113 JsonValue::Number(JsonNumber::I64(-9_223_372_036_854_775_808)),
3114 JsonValue::Number(JsonNumber::U64(u64::MAX)),
3115 JsonValue::Number(JsonNumber::F64(12345.125)),
3116 JsonValue::Array(vec![
3117 JsonValue::Bool(true),
3118 JsonValue::String("nested".into()),
3119 JsonValue::Object(Map::from(vec![("x".into(), 1u64.into())])),
3120 ]),
3121 ];
3122 for value in values {
3123 let text = value.to_json_string().unwrap();
3124 let reparsed = parse_json(&text).unwrap();
3125 assert_json_equivalent(&value, &reparsed);
3126 }
3127 }
3128
3129 #[test]
3130 fn deterministic_fuzz_roundtrip_strings_and_values() {
3131 let mut rng = Rng::new(0x5eed_1234_5678_9abc);
3132 for _ in 0..2_000 {
3133 let input = random_string(&mut rng, 48);
3134 let escaped = escape_json_string(&input);
3135 let parsed = parse_json(&escaped).unwrap();
3136 assert_eq!(parsed, JsonValue::String(input));
3137 }
3138
3139 for _ in 0..1_000 {
3140 let value = random_json_value(&mut rng, 0, 4);
3141 let text = value.to_json_string().unwrap();
3142 let reparsed = parse_json(&text).unwrap();
3143 assert_json_equivalent(&value, &reparsed);
3144 }
3145 }
3146
3147 fn assert_json_equivalent(expected: &JsonValue, actual: &JsonValue) {
3148 match (expected, actual) {
3149 (JsonValue::Null, JsonValue::Null) => {}
3150 (JsonValue::Bool(a), JsonValue::Bool(b)) => assert_eq!(a, b),
3151 (JsonValue::String(a), JsonValue::String(b)) => assert_eq!(a, b),
3152 (JsonValue::Number(a), JsonValue::Number(b)) => assert_numbers_equivalent(a, b),
3153 (JsonValue::Array(a), JsonValue::Array(b)) => {
3154 assert_eq!(a.len(), b.len());
3155 for (left, right) in a.iter().zip(b.iter()) {
3156 assert_json_equivalent(left, right);
3157 }
3158 }
3159 (JsonValue::Object(a), JsonValue::Object(b)) => {
3160 assert_eq!(a.len(), b.len());
3161 for ((left_key, left_value), (right_key, right_value)) in a.iter().zip(b.iter()) {
3162 assert_eq!(left_key, right_key);
3163 assert_json_equivalent(left_value, right_value);
3164 }
3165 }
3166 _ => panic!("json values differ: expected {expected:?}, actual {actual:?}"),
3167 }
3168 }
3169
3170 fn assert_numbers_equivalent(expected: &JsonNumber, actual: &JsonNumber) {
3171 match (expected, actual) {
3172 (JsonNumber::I64(a), JsonNumber::I64(b)) => assert_eq!(a, b),
3173 (JsonNumber::U64(a), JsonNumber::U64(b)) => assert_eq!(a, b),
3174 (JsonNumber::F64(a), JsonNumber::F64(b)) => assert_eq!(a.to_bits(), b.to_bits()),
3175 (JsonNumber::I64(a), JsonNumber::U64(b)) if *a >= 0 => assert_eq!(*a as u64, *b),
3176 (JsonNumber::U64(a), JsonNumber::I64(b)) if *b >= 0 => assert_eq!(*a, *b as u64),
3177 (JsonNumber::I64(a), JsonNumber::F64(b)) => assert_eq!(*a as f64, *b),
3178 (JsonNumber::U64(a), JsonNumber::F64(b)) => assert_eq!(*a as f64, *b),
3179 (JsonNumber::F64(a), JsonNumber::I64(b)) => assert_eq!(*a, *b as f64),
3180 (JsonNumber::F64(a), JsonNumber::U64(b)) => assert_eq!(*a, *b as f64),
3181 (left, right) => panic!("json numbers differ: expected {left:?}, actual {right:?}"),
3182 }
3183 }
3184
3185 #[derive(Clone, Debug)]
3186 struct Rng {
3187 state: u64,
3188 }
3189
3190 impl Rng {
3191 fn new(seed: u64) -> Self {
3192 Self { state: seed }
3193 }
3194
3195 fn next_u64(&mut self) -> u64 {
3196 self.state = self
3197 .state
3198 .wrapping_mul(6364136223846793005)
3199 .wrapping_add(1442695040888963407);
3200 self.state
3201 }
3202
3203 fn choose(&mut self, upper_exclusive: usize) -> usize {
3204 (self.next_u64() % upper_exclusive as u64) as usize
3205 }
3206
3207 fn bool(&mut self) -> bool {
3208 (self.next_u64() & 1) == 1
3209 }
3210 }
3211
3212 fn random_string(rng: &mut Rng, max_len: usize) -> String {
3213 let len = rng.choose(max_len + 1);
3214 let mut out = String::new();
3215 for _ in 0..len {
3216 let ch = match rng.choose(12) {
3217 0 => '"',
3218 1 => '\\',
3219 2 => '\n',
3220 3 => '\r',
3221 4 => '\t',
3222 5 => '\u{0007}',
3223 6 => 'λ',
3224 7 => '🚀',
3225 8 => '☃',
3226 _ => (b'a' + rng.choose(26) as u8) as char,
3227 };
3228 out.push(ch);
3229 }
3230 out
3231 }
3232
3233 fn random_json_value(rng: &mut Rng, depth: usize, max_depth: usize) -> JsonValue {
3234 if depth >= max_depth {
3235 return random_leaf(rng);
3236 }
3237 match rng.choose(7) {
3238 0 | 1 | 2 | 3 => random_leaf(rng),
3239 4 => {
3240 let len = rng.choose(5);
3241 let mut values = Vec::with_capacity(len);
3242 for _ in 0..len {
3243 values.push(random_json_value(rng, depth + 1, max_depth));
3244 }
3245 JsonValue::Array(values)
3246 }
3247 _ => {
3248 let len = rng.choose(5);
3249 let mut entries = Vec::with_capacity(len);
3250 for index in 0..len {
3251 entries.push((
3252 format!("k{depth}_{index}_{}", random_string(rng, 6)),
3253 random_json_value(rng, depth + 1, max_depth),
3254 ));
3255 }
3256 JsonValue::Object(Map::from(entries))
3257 }
3258 }
3259 }
3260
3261 fn random_leaf(rng: &mut Rng) -> JsonValue {
3262 match rng.choose(6) {
3263 0 => JsonValue::Null,
3264 1 => JsonValue::Bool(rng.bool()),
3265 2 => JsonValue::String(random_string(rng, 24)),
3266 3 => JsonValue::Number(JsonNumber::I64(
3267 (rng.next_u64() >> 1) as i64 * if rng.bool() { 1 } else { -1 },
3268 )),
3269 4 => JsonValue::Number(JsonNumber::U64(rng.next_u64())),
3270 _ => {
3271 let mantissa = (rng.next_u64() % 1_000_000) as f64 / 1000.0;
3272 let sign = if rng.bool() { 1.0 } else { -1.0 };
3273 JsonValue::Number(JsonNumber::F64(sign * mantissa))
3274 }
3275 }
3276 }
3277}