Skip to main content

json_syntax/
array.rs

1use crate::{JsonCodeMap, JsonFragment, JsonValue, code_map::JsonMapped};
2
3/// JSON array slice.
4pub type JsonArray = [JsonValue];
5
6/// Owned JSON array.
7pub type JsonArrayBuf = Vec<JsonValue>;
8
9/// Trait for JSON array types like `Vec<Value>` and `[Value]`.
10pub trait JsonArrayExt {
11	fn iter_mapped<'m>(&self, code_map: &'m JsonCodeMap, offset: usize) -> IterMapped<'_, 'm>;
12
13	fn get_fragment(&self, index: usize) -> Result<JsonFragment<'_>, usize>;
14}
15
16/// Trait for owned JSON array types like `Vec<Value>`.
17pub trait JsonArrayBufExt: Sized + JsonArrayExt {
18	fn into_iter_mapped<'m>(self, code_map: &'m JsonCodeMap, offset: usize) -> IntoIterMapped<'m>;
19}
20
21impl JsonArrayExt for JsonArray {
22	fn iter_mapped<'m>(&self, code_map: &'m JsonCodeMap, offset: usize) -> IterMapped<'_, 'm> {
23		IterMapped {
24			items: self.iter(),
25			code_map,
26			offset: offset + 1,
27		}
28	}
29
30	fn get_fragment(&self, mut index: usize) -> Result<JsonFragment<'_>, usize> {
31		for v in self {
32			match v.get_fragment(index) {
33				Ok(value) => return Ok(value),
34				Err(i) => index = i,
35			}
36		}
37
38		Err(index)
39	}
40}
41
42impl JsonArrayExt for JsonArrayBuf {
43	fn iter_mapped<'m>(&self, code_map: &'m JsonCodeMap, offset: usize) -> IterMapped<'_, 'm> {
44		self.as_slice().iter_mapped(code_map, offset)
45	}
46
47	fn get_fragment(&self, index: usize) -> Result<JsonFragment<'_>, usize> {
48		self.as_slice().get_fragment(index)
49	}
50}
51
52impl JsonArrayBufExt for JsonArrayBuf {
53	fn into_iter_mapped<'m>(self, code_map: &'m JsonCodeMap, offset: usize) -> IntoIterMapped<'m> {
54		IntoIterMapped {
55			items: self.into_iter(),
56			code_map,
57			offset: offset + 1,
58		}
59	}
60}
61
62pub struct IterMapped<'a, 'm> {
63	items: std::slice::Iter<'a, JsonValue>,
64	code_map: &'m JsonCodeMap,
65	offset: usize,
66}
67
68impl<'a, 'm> Iterator for IterMapped<'a, 'm> {
69	type Item = JsonMapped<&'a JsonValue>;
70
71	fn next(&mut self) -> Option<Self::Item> {
72		self.items.next().map(|item| {
73			let offset = self.offset;
74			self.offset += self.code_map.get(self.offset).unwrap().volume;
75			JsonMapped(item, offset)
76		})
77	}
78}
79
80pub struct IntoIterMapped<'m> {
81	items: std::vec::IntoIter<JsonValue>,
82	code_map: &'m JsonCodeMap,
83	offset: usize,
84}
85
86impl<'m> Iterator for IntoIterMapped<'m> {
87	type Item = JsonMapped<JsonValue>;
88
89	fn next(&mut self) -> Option<Self::Item> {
90		self.items.next().map(|item| {
91			let offset = self.offset;
92			self.offset += self.code_map.get(self.offset).unwrap().volume;
93			JsonMapped(item, offset)
94		})
95	}
96}