Skip to main content

json_syntax/
object.rs

1use crate::code_map::{JsonCodeMapOffset, JsonMapped};
2use crate::lexical::{JsonBorrowLexical, JsonLexicalEq, JsonLexicalHash, JsonLexicalPartialEq};
3use crate::{JsonCodeMap, JsonFragment, JsonValue};
4use btree_indexmap::{BTreeIndexMultiMap, Comparable};
5use core::fmt;
6use core::hash::{Hash, Hasher};
7
8pub use btree_indexmap::multi_map::IndexesIter;
9
10/// Object key stack capacity.
11///
12/// If the key is longer than this value,
13/// it will be stored on the heap.
14pub const KEY_CAPACITY: usize = 16;
15
16/// Object key.
17pub type Key = smallstr::SmallString<[u8; KEY_CAPACITY]>;
18
19/// Object entry.
20pub type Entry = (Key, JsonValue);
21
22/// Object entry reference.
23pub type EntryRef<'a> = (&'a Key, &'a JsonValue);
24
25fn entry_ref((k, v): &Entry) -> EntryRef<'_> {
26	(k, v)
27}
28
29fn get_entry_fragment<'a>(entry: &'a Entry, index: usize) -> Result<JsonFragment<'a>, usize> {
30	match index {
31		0 => Ok(JsonFragment::Entry(entry_ref(entry))),
32		1 => Ok(JsonFragment::Key(&entry.0)),
33		_ => entry.1.get_fragment(index - 2),
34	}
35}
36
37/// Object entry, with code map information.
38pub type MappedEntry = JsonMapped<(JsonMapped<Key>, JsonMapped<JsonValue>)>;
39
40fn mapped_entry(
41	(key, value): Entry,
42	offset: usize,
43	key_offset: usize,
44	value_offset: usize,
45) -> MappedEntry {
46	JsonMapped(
47		(JsonMapped(key, key_offset), JsonMapped(value, value_offset)),
48		offset,
49	)
50}
51
52/// Object entry reference, with code map information.
53pub type MappedEntryRef<'a> = JsonMapped<(JsonMapped<&'a Key>, JsonMapped<&'a JsonValue>)>;
54
55fn mapped_entry_ref(
56	(key, value): EntryRef,
57	offset: usize,
58	key_offset: usize,
59	value_offset: usize,
60) -> MappedEntryRef {
61	JsonMapped(
62		(JsonMapped(key, key_offset), JsonMapped(value, value_offset)),
63		offset,
64	)
65}
66
67pub type IndexedMappedEntry<'a> = (usize, MappedEntryRef<'a>);
68
69pub type IndexedMappedValue<'a> = (usize, JsonMapped<&'a JsonValue>);
70
71/// JSON object.
72///
73/// # Comparison
74///
75/// The `PartialEq` and `PartialOrd` implementations will compare the JSON
76/// objects semantically, without regard for the entries indexes. The only
77/// exception is when one key has multiple values, in which cases the values are
78/// ordered by index. It is possible to compare the lexical representation of
79/// objects (where the entries indexes matter) by using the
80/// [`BorrowJsonLexical::as_lexical`] method on both ends and comparing the
81/// results.
82#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct JsonObject {
84	map: BTreeIndexMultiMap<Key, JsonValue>,
85}
86
87impl Default for JsonObject {
88	fn default() -> Self {
89		Self {
90			map: BTreeIndexMultiMap::new(),
91		}
92	}
93}
94
95impl JsonObject {
96	pub fn new() -> Self {
97		Self::default()
98	}
99
100	pub fn from_vec(entries: Vec<(Key, JsonValue)>) -> Self {
101		Self {
102			map: entries.into_iter().collect(),
103		}
104	}
105
106	pub fn capacity(&self) -> usize {
107		self.map.capacity()
108	}
109
110	pub fn len(&self) -> usize {
111		self.map.len()
112	}
113
114	pub fn is_empty(&self) -> bool {
115		self.map.is_empty()
116	}
117
118	pub fn get_fragment(&self, mut index: usize) -> Result<JsonFragment<'_>, usize> {
119		for e in self.map.as_entries() {
120			match get_entry_fragment(e, index) {
121				Ok(value) => return Ok(value),
122				Err(i) => index = i,
123			}
124		}
125
126		Err(index)
127	}
128
129	pub fn entries(&self) -> &[Entry] {
130		self.map.as_entries()
131	}
132
133	pub fn iter(&self) -> Iter<'_> {
134		self.map.iter()
135	}
136
137	pub fn iter_mut(&mut self) -> IterMut<'_> {
138		self.map.iter_mut()
139	}
140
141	pub fn iter_mapped<'m>(&self, code_map: &'m JsonCodeMap, offset: usize) -> IterMapped<'_, 'm> {
142		IterMapped {
143			entries: self.map.iter(),
144			code_map,
145			offset: offset + 1,
146		}
147	}
148
149	pub fn into_iter_mapped<'m>(
150		self,
151		code_map: &'m JsonCodeMap,
152		offset: usize,
153	) -> IntoIterMapped<'m> {
154		IntoIterMapped {
155			entries: self.map.into_iter(),
156			code_map,
157			offset: offset + 1,
158		}
159	}
160
161	pub fn iter_sorted(&self) -> IterSorted<'_> {
162		self.map.iter_sorted()
163	}
164
165	pub fn iter_mut_sorted(&mut self) -> IterMutSorted<'_> {
166		self.map.iter_mut_sorted()
167	}
168
169	pub fn into_iter_sorted(self) -> IntoIterSorted {
170		self.map.into_iter_sorted()
171	}
172
173	/// Checks if this object contains the given key.
174	///
175	/// Runs in `O(log(n))` (average).
176	pub fn contains_key<Q>(&self, key: &Q) -> bool
177	where
178		Q: ?Sized + Comparable<Key>,
179	{
180		self.map.contains_key(key)
181	}
182
183	/// Returns an iterator over the values matching the given key.
184	///
185	/// Runs in `O(log(n))` (average).
186	pub fn get<Q>(&self, key: &Q) -> Get<'_>
187	where
188		Q: ?Sized + Comparable<Key>,
189	{
190		self.map.get(key)
191	}
192
193	/// Returns an iterator over the values matching the given key.
194	///
195	/// Runs in `O(log(n))` (average).
196	pub fn get_mut<Q>(&mut self, key: &Q) -> GetMut<'_>
197	where
198		Q: ?Sized + Comparable<Key>,
199	{
200		self.map.get_mut(key)
201	}
202
203	/// Returns the unique entry value matching the given key.
204	///
205	/// Returns an error if multiple entries match the key.
206	///
207	/// Runs in `O(log(n))` (average).
208	pub fn get_unique<Q>(&self, key: &Q) -> Result<Option<&JsonValue>, DuplicateEntry<EntryRef<'_>>>
209	where
210		Q: ?Sized + Comparable<Key>,
211	{
212		let mut entries = self.map.get_entries(key);
213
214		match entries.next() {
215			Some(entry) => match entries.next() {
216				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
217				None => Ok(Some(entry.1)),
218			},
219			None => Ok(None),
220		}
221	}
222
223	/// Returns the unique entry value matching the given key.
224	///
225	/// Returns an error if multiple entries match the key.
226	///
227	/// Runs in `O(log(n))` (average).
228	pub fn get_unique_mut<Q>(
229		&mut self,
230		key: &Q,
231	) -> Result<Option<&mut JsonValue>, DuplicateEntry<EntryRef<'_>>>
232	where
233		Q: ?Sized + Comparable<Key>,
234	{
235		let mut entries = self.map.get_entries_mut(key);
236
237		match entries.next() {
238			Some(entry) => match entries.next() {
239				Some(duplicate) => {
240					let entry = (entry.0, &*entry.1);
241					let duplicate = (duplicate.0, &*duplicate.1);
242					Err(DuplicateEntry::new(entry, duplicate))
243				}
244				None => Ok(Some(entry.1)),
245			},
246			None => Ok(None),
247		}
248	}
249
250	/// Returns an iterator over the entries matching the given key.
251	///
252	/// Runs in `O(log(n))` (average).
253	pub fn get_entries<Q>(&self, key: &Q) -> GetEntries<'_>
254	where
255		Q: ?Sized + Comparable<Key>,
256	{
257		self.map.get_entries(key)
258	}
259
260	/// Returns the unique entry matching the given key.
261	///
262	/// Returns an error if multiple entries match the key.
263	///
264	/// Runs in `O(log(n))` (average).
265	pub fn get_unique_entry<Q>(
266		&self,
267		key: &Q,
268	) -> Result<Option<EntryRef<'_>>, DuplicateEntry<EntryRef<'_>>>
269	where
270		Q: ?Sized + Comparable<Key>,
271	{
272		let mut entries = self.get_entries(key);
273
274		match entries.next() {
275			Some(entry) => match entries.next() {
276				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
277				None => Ok(Some(entry)),
278			},
279			None => Ok(None),
280		}
281	}
282
283	/// Returns an iterator over the values matching the given key.
284	///
285	/// Runs in `O(log(n))` (average).
286	pub fn get_indexed<Q>(&self, key: &Q) -> GetIndexed<'_>
287	where
288		Q: ?Sized + Comparable<Key>,
289	{
290		self.map.get_indexed(key)
291	}
292
293	/// Returns an iterator over the entries matching the given key.
294	///
295	/// Runs in `O(log(n))` (average).
296	pub fn get_indexed_entries<Q>(&self, key: &Q) -> GetIndexedEntries<'_>
297	where
298		Q: ?Sized + Comparable<Key>,
299	{
300		self.map.get_indexed_entries(key)
301	}
302
303	/// Returns the (first) value associated to `key`, or insert a `key`-`value`
304	/// entry where `value` is returned by the given function `f`.
305	pub fn get_or_insert_with<Q>(
306		&mut self,
307		key: impl Into<Key>,
308		f: impl FnOnce() -> JsonValue,
309	) -> Get<'_> {
310		self.map.get_or_insert_with(key.into(), f)
311	}
312
313	/// Returns a mutable reference to the (first) value associated to `key`, or
314	/// insert a `key`-`value` entry where `value` is returned by the given
315	/// function `f`.
316	pub fn get_or_insert_mut_with<Q>(
317		&mut self,
318		key: impl Into<Key>,
319		f: impl FnOnce() -> JsonValue,
320	) -> GetMut<'_> {
321		self.map.get_or_insert_mut_with(key.into(), f)
322	}
323
324	pub fn index_of<Q>(&self, key: &Q) -> Option<usize>
325	where
326		Q: ?Sized + Comparable<Key>,
327	{
328		self.map.index_of(key)
329	}
330
331	pub fn indexes_of<Q>(&self, key: &Q) -> IndexesIter<'_>
332	where
333		Q: ?Sized + Comparable<Key>,
334	{
335		self.map.indexes_of(key)
336	}
337
338	pub fn redundant_index_of<Q>(&self, key: &Q) -> Option<usize>
339	where
340		Q: ?Sized + Comparable<Key>,
341	{
342		self.map.indexes_of(key).nth(1)
343	}
344
345	/// Returns an iterator over the mapped entries matching the given key.
346	///
347	/// Runs in `O(n)` (average). `O(log(n))` to find the entry, `O(n)` to
348	/// compute the entry fragment offset.
349	pub fn get_mapped_entries<'m, Q>(
350		&self,
351		code_map: &'m JsonCodeMap,
352		offset: usize,
353		key: &Q,
354	) -> GetMappedEntries<'_, 'm>
355	where
356		Q: ?Sized + Comparable<Key>,
357	{
358		GetMappedEntries {
359			indexes: self.map.indexes_of(key),
360			object: self,
361			code_map,
362			offset: offset + 1,
363			last_index: 0,
364		}
365	}
366
367	/// Returns the unique mapped entry matching the given key.
368	///
369	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
370	/// the entry fragment offset.
371	pub fn get_unique_mapped_entry<Q>(
372		&self,
373		code_map: &JsonCodeMap,
374		offset: usize,
375		key: &Q,
376	) -> Result<Option<MappedEntryRef<'_>>, DuplicateEntry<MappedEntryRef<'_>>>
377	where
378		Q: ?Sized + Comparable<Key>,
379	{
380		let mut entries = self.get_mapped_entries(code_map, offset, key);
381
382		match entries.next() {
383			Some(entry) => match entries.next() {
384				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
385				None => Ok(Some(entry)),
386			},
387			None => Ok(None),
388		}
389	}
390
391	/// Returns an iterator over the mapped entries matching the given key, with
392	/// their index.
393	///
394	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
395	/// the entry fragment offset.
396	pub fn get_mapped_entries_with_index<'m, Q>(
397		&self,
398		code_map: &'m JsonCodeMap,
399		offset: usize,
400		key: &Q,
401	) -> GetIndexedMappedEntries<'_, 'm>
402	where
403		Q: ?Sized + Comparable<Key>,
404	{
405		GetIndexedMappedEntries {
406			indexes: self.map.indexes_of(key),
407			object: self,
408			code_map,
409			offset: offset + 1,
410			last_index: 0,
411		}
412	}
413
414	/// Returns the unique mapped entry matching the given key, with its index.
415	///
416	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
417	/// the entry fragment offset.
418	pub fn get_unique_mapped_entry_with_index<Q>(
419		&self,
420		code_map: &JsonCodeMap,
421		offset: usize,
422		key: &Q,
423	) -> Result<Option<IndexedMappedEntry<'_>>, DuplicateEntry<IndexedMappedEntry<'_>>>
424	where
425		Q: ?Sized + Comparable<Key>,
426	{
427		let mut entries = self.get_mapped_entries_with_index(code_map, offset, key);
428
429		match entries.next() {
430			Some(entry) => match entries.next() {
431				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
432				None => Ok(Some(entry)),
433			},
434			None => Ok(None),
435		}
436	}
437
438	/// Returns an iterator over the mapped values matching the given key.
439	///
440	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
441	/// the entry fragment offset.
442	pub fn get_mapped<'m, Q>(
443		&self,
444		code_map: &'m JsonCodeMap,
445		offset: usize,
446		key: &Q,
447	) -> GetMapped<'_, 'm>
448	where
449		Q: ?Sized + Comparable<Key>,
450	{
451		GetMapped {
452			indexes: self.map.indexes_of(key),
453			object: self,
454			code_map,
455			offset: offset + 1,
456			last_index: 0,
457		}
458	}
459
460	/// Returns the unique mapped values matching the given key.
461	///
462	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
463	/// the entry fragment offset.
464	pub fn get_unique_mapped<Q>(
465		&self,
466		code_map: &JsonCodeMap,
467		offset: usize,
468		key: &Q,
469	) -> Result<Option<JsonMapped<&JsonValue>>, DuplicateEntry<JsonMapped<&JsonValue>>>
470	where
471		Q: ?Sized + Comparable<Key>,
472	{
473		let mut entries = self.get_mapped(code_map, offset, key);
474
475		match entries.next() {
476			Some(entry) => match entries.next() {
477				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
478				None => Ok(Some(entry)),
479			},
480			None => Ok(None),
481		}
482	}
483
484	/// Returns an iterator over the mapped values matching the given key, with
485	/// their index.
486	///
487	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
488	/// the entry fragment offset.
489	pub fn get_indexed_mapped<'m, Q>(
490		&self,
491		code_map: &'m JsonCodeMap,
492		offset: usize,
493		key: &Q,
494	) -> GetIndexedMapped<'_, 'm>
495	where
496		Q: ?Sized + Comparable<Key>,
497	{
498		GetIndexedMapped {
499			indexes: self.map.indexes_of(key),
500			object: self,
501			code_map,
502			offset: offset + 1,
503			last_index: 0,
504		}
505	}
506
507	/// Returns the unique mapped values matching the given key, with its index.
508	///
509	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
510	/// the entry fragment offset.
511	pub fn get_unique_mapped_with_index<Q>(
512		&self,
513		code_map: &JsonCodeMap,
514		offset: usize,
515		key: &Q,
516	) -> Result<Option<IndexedMappedValue<'_>>, DuplicateEntry<IndexedMappedValue<'_>>>
517	where
518		Q: ?Sized + Comparable<Key>,
519	{
520		let mut entries = self.get_indexed_mapped(code_map, offset, key);
521
522		match entries.next() {
523			Some(entry) => match entries.next() {
524				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
525				None => Ok(Some(entry)),
526			},
527			None => Ok(None),
528		}
529	}
530
531	pub fn first(&self) -> Option<EntryRef<'_>> {
532		self.map.first()
533	}
534
535	pub fn last(&self) -> Option<EntryRef<'_>> {
536		self.map.last()
537	}
538
539	/// Push the given key-value pair to the end of the object.
540	///
541	/// Returns `true` if the key was not already present in the object,
542	/// and `false` otherwise.
543	/// Any previous entry matching the key is **not** overridden: duplicates
544	/// are preserved, in order.
545	///
546	/// Runs in `O(1)`.
547	pub fn push_back(&mut self, key: impl Into<Key>, value: JsonValue) -> (usize, bool) {
548		self.map.push_back(key.into(), value)
549	}
550
551	pub fn push_entry_back(&mut self, (key, value): Entry) -> (usize, bool) {
552		self.map.push_back(key, value)
553	}
554
555	/// Push the given key-value pair to the top of the object.
556	///
557	/// Returns `true` if the key was not already present in the object,
558	/// and `false` otherwise.
559	/// Any previous entry matching the key is **not** overridden: duplicates
560	/// are preserved, in order.
561	///
562	/// Runs in `O(n)`.
563	pub fn push_front(&mut self, key: impl Into<Key>, value: JsonValue) -> bool {
564		self.map.push_front(key.into(), value)
565	}
566
567	pub fn push_entry_front(&mut self, (key, value): Entry) -> bool {
568		self.map.push_front(key, value)
569	}
570
571	/// Removes the entry at the given index `i`.
572	pub fn swap_remove_at(&mut self, i: usize) -> Option<Entry> {
573		self.map.swap_remove_at(i)
574	}
575
576	/// Removes the entry at the given index `i`.
577	pub fn shift_remove_at(&mut self, i: usize) -> Option<Entry> {
578		self.map.shift_remove_at(i)
579	}
580
581	/// Inserts the given key-value pair.
582	///
583	/// If one or more entries are already matching the given key,
584	/// all of them are removed and returned in the resulting iterator.
585	/// Otherwise, `None` is returned.
586	pub fn shift_insert(&mut self, key: impl Into<Key>, value: JsonValue) -> ShiftInsert<'_> {
587		self.map.shift_insert(key.into(), value)
588	}
589
590	pub fn swap_insert(&mut self, key: impl Into<Key>, value: JsonValue) -> SwapInsert<'_> {
591		self.map.swap_insert(key.into(), value)
592	}
593
594	/// Inserts the given key-value pair on top of the object.
595	///
596	/// If one or more entries are already matching the given key,
597	/// all of them are removed and returned in the resulting iterator.
598	pub fn shift_insert_front(
599		&mut self,
600		key: impl Into<Key>,
601		value: JsonValue,
602	) -> ShiftInsertFront<'_> {
603		self.map.shift_insert_front(key.into(), value)
604	}
605
606	pub fn swap_insert_front(
607		&mut self,
608		key: impl Into<Key>,
609		value: JsonValue,
610	) -> SwapInsertFront<'_> {
611		self.map.swap_insert_front(key.into(), value)
612	}
613
614	pub fn shift_insert_back_full(
615		&mut self,
616		key: impl Into<Key>,
617		value: JsonValue,
618	) -> (usize, ShiftInsertBack<'_>) {
619		self.map.shift_insert_back_full(key.into(), value)
620	}
621
622	pub fn shift_insert_back(
623		&mut self,
624		key: impl Into<Key>,
625		value: JsonValue,
626	) -> ShiftInsertBack<'_> {
627		self.map.shift_insert_back(key.into(), value)
628	}
629
630	/// Alias of [`Self::shift_insert_back`].
631	pub fn insert(&mut self, key: impl Into<Key>, value: JsonValue) -> ShiftInsertBack<'_> {
632		self.shift_insert_back(key, value)
633	}
634
635	pub fn swap_insert_back_full(
636		&mut self,
637		key: impl Into<Key>,
638		value: JsonValue,
639	) -> (usize, SwapInsertBack<'_>) {
640		self.map.swap_insert_back_full(key.into(), value)
641	}
642
643	pub fn swap_insert_back(
644		&mut self,
645		key: impl Into<Key>,
646		value: JsonValue,
647	) -> SwapInsertBack<'_> {
648		self.map.swap_insert_back(key.into(), value)
649	}
650
651	pub fn shift_remove_indexed_entries<Q>(&mut self, key: &Q) -> ShiftRemoveIndexedEntries<'_>
652	where
653		Q: ?Sized + Comparable<Key>,
654	{
655		self.map.shift_remove_indexed_entries(key)
656	}
657
658	/// Remove all entries associated to the given key.
659	pub fn shift_remove_entries<Q>(&mut self, key: &Q) -> ShiftRemoveEntries<'_>
660	where
661		Q: ?Sized + Comparable<Key>,
662	{
663		self.map.shift_remove_entries(key)
664	}
665
666	/// Remove all entries associated to the given key.
667	pub fn shift_remove<Q>(&mut self, key: &Q) -> ShiftRemove<'_>
668	where
669		Q: ?Sized + Comparable<Key>,
670	{
671		self.map.shift_remove(key)
672	}
673
674	/// Alias of [`Self::shift_remove`].
675	pub fn remove<Q>(&mut self, key: &Q) -> ShiftRemove<'_>
676	where
677		Q: ?Sized + Comparable<Key>,
678	{
679		self.shift_remove(key)
680	}
681
682	/// Alias of [`Self::shift_remove_unique`].
683	pub fn remove_unique<Q>(&mut self, key: &Q) -> Result<Option<Entry>, DuplicateEntry<Entry>>
684	where
685		Q: ?Sized + Comparable<Key>,
686	{
687		self.shift_remove_unique(key)
688	}
689
690	pub fn swap_remove_indexed_entries<Q>(&mut self, key: &Q) -> SwapRemoveIndexedEntries<'_>
691	where
692		Q: ?Sized + Comparable<Key>,
693	{
694		self.map.swap_remove_indexed_entries(key)
695	}
696
697	pub fn swap_remove_entries<Q>(&mut self, key: &Q) -> SwapRemoveEntries<'_>
698	where
699		Q: ?Sized + Comparable<Key>,
700	{
701		self.map.swap_remove_entries(key)
702	}
703
704	pub fn swap_remove<Q>(&mut self, key: &Q) -> SwapRemove<'_>
705	where
706		Q: ?Sized + Comparable<Key>,
707	{
708		self.map.swap_remove(key)
709	}
710
711	/// Remove the unique entry associated to the given key.
712	///
713	/// Returns an error if multiple entries match the key.
714	pub fn swap_remove_unique<Q>(&mut self, key: &Q) -> Result<Option<Entry>, DuplicateEntry<Entry>>
715	where
716		Q: ?Sized + Comparable<Key>,
717	{
718		let mut entries = self.swap_remove_entries(key);
719
720		match entries.next() {
721			Some(entry) => match entries.next() {
722				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
723				None => Ok(Some(entry)),
724			},
725			None => Ok(None),
726		}
727	}
728
729	/// Remove the unique entry associated to the given key.
730	///
731	/// Returns an error if multiple entries match the key.
732	pub fn shift_remove_unique<Q>(
733		&mut self,
734		key: &Q,
735	) -> Result<Option<Entry>, DuplicateEntry<Entry>>
736	where
737		Q: ?Sized + Comparable<Key>,
738	{
739		let mut entries = self.shift_remove_entries(key);
740
741		match entries.next() {
742			Some(entry) => match entries.next() {
743				Some(duplicate) => Err(DuplicateEntry::new(entry, duplicate)),
744				None => Ok(Some(entry)),
745			},
746			None => Ok(None),
747		}
748	}
749
750	/// Sort the entries by key name.
751	///
752	/// The relative order of entries with the same key is unchanged.
753	pub fn sort(&mut self) {
754		self.map.sort();
755	}
756
757	/// Puts this JSON object in canonical form according to
758	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
759	///
760	/// This will canonicalize the entries and sort them by key.
761	/// The relative order of entries with the same key is unchanged.
762	#[cfg(feature = "canonicalize")]
763	pub fn canonicalize_with(&mut self, buffer: &mut ryu_js::Buffer) {
764		for (_, item) in self.iter_mut() {
765			item.canonicalize_with(buffer);
766		}
767
768		self.sort()
769	}
770
771	/// Puts this JSON object in canonical form according to
772	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
773	#[cfg(feature = "canonicalize")]
774	pub fn canonicalize(&mut self) {
775		let mut buffer = ryu_js::Buffer::new();
776		self.canonicalize_with(&mut buffer)
777	}
778}
779
780pub type Iter<'a> = btree_indexmap::multi_map::Iter<'a, Key, JsonValue>;
781
782pub type IterMut<'a> = btree_indexmap::multi_map::IterMut<'a, Key, JsonValue>;
783
784pub type IntoIter = btree_indexmap::multi_map::IntoIter<Key, JsonValue>;
785
786pub type IterSorted<'a> = btree_indexmap::multi_map::IterSorted<'a, Key, JsonValue>;
787
788pub type IterMutSorted<'a> = btree_indexmap::multi_map::IterMutSorted<'a, Key, JsonValue>;
789
790pub type IntoIterSorted = btree_indexmap::multi_map::IntoIterSorted<Key, JsonValue>;
791
792pub type Get<'a> = btree_indexmap::multi_map::Get<'a, Key, JsonValue>;
793
794pub type GetIndexed<'a> = btree_indexmap::multi_map::GetIndexed<'a, Key, JsonValue>;
795
796pub type GetEntries<'a> = btree_indexmap::multi_map::GetEntries<'a, Key, JsonValue>;
797
798pub type GetIndexedEntries<'a> = btree_indexmap::multi_map::GetIndexedEntries<'a, Key, JsonValue>;
799
800pub type GetMut<'a> = btree_indexmap::multi_map::GetMut<'a, Key, JsonValue>;
801
802pub type ShiftInsert<'a> = btree_indexmap::multi_map::ShiftInsert<'a, Key, JsonValue>;
803
804pub type SwapInsert<'a> = btree_indexmap::multi_map::SwapInsert<'a, Key, JsonValue>;
805
806pub type ShiftInsertBack<'a> = btree_indexmap::multi_map::ShiftInsertBack<'a, Key, JsonValue>;
807
808pub type SwapInsertBack<'a> = btree_indexmap::multi_map::SwapInsertBack<'a, Key, JsonValue>;
809
810pub type ShiftInsertFront<'a> = btree_indexmap::multi_map::ShiftInsertFront<'a, Key, JsonValue>;
811
812pub type SwapInsertFront<'a> = btree_indexmap::multi_map::SwapInsertFront<'a, Key, JsonValue>;
813
814pub type ShiftRemoveIndexedEntries<'a> =
815	btree_indexmap::multi_map::ShiftRemoveIndexedEntries<'a, Key, JsonValue>;
816
817pub type ShiftRemoveEntries<'a> = btree_indexmap::multi_map::ShiftRemoveEntries<'a, Key, JsonValue>;
818
819pub type ShiftRemove<'a> = btree_indexmap::multi_map::ShiftRemove<'a, Key, JsonValue>;
820
821pub type SwapRemoveIndexedEntries<'a> =
822	btree_indexmap::multi_map::SwapRemoveIndexedEntries<'a, Key, JsonValue>;
823
824pub type SwapRemoveEntries<'a> = btree_indexmap::multi_map::SwapRemoveEntries<'a, Key, JsonValue>;
825
826pub type SwapRemove<'a> = btree_indexmap::multi_map::SwapRemove<'a, Key, JsonValue>;
827
828pub struct IterMapped<'a, 'm> {
829	entries: Iter<'a>,
830	code_map: &'m JsonCodeMap,
831	offset: usize,
832}
833
834impl<'a, 'm> Iterator for IterMapped<'a, 'm> {
835	type Item = MappedEntryRef<'a>;
836
837	fn next(&mut self) -> Option<Self::Item> {
838		self.entries.next().map(|e| {
839			let offset = self.offset;
840			self.offset += 2 + self.code_map.get(self.offset + 2).unwrap().volume;
841			mapped_entry_ref(e, offset, offset + 1, offset + 2)
842		})
843	}
844}
845
846pub struct IntoIterMapped<'m> {
847	entries: IntoIter,
848	code_map: &'m JsonCodeMap,
849	offset: JsonCodeMapOffset,
850}
851
852impl<'m> Iterator for IntoIterMapped<'m> {
853	type Item = MappedEntry;
854
855	fn next(&mut self) -> Option<Self::Item> {
856		self.entries.next().map(|e| {
857			let offset = self.offset;
858			self.offset += 2 + self.code_map.get(self.offset + 2).unwrap().volume;
859			mapped_entry(e, offset, offset + 1, offset + 2)
860		})
861	}
862}
863
864macro_rules! mapped_entries_iter {
865	($($id:ident <$lft:lifetime> {
866		type Item = $item:ty ;
867
868		fn next(&mut $self:ident, $index:ident) { $e:expr }
869	})*) => {
870		$(
871			pub struct $id<$lft, 'm> {
872				indexes: IndexesIter<$lft>,
873				object: &$lft JsonObject,
874				code_map: &'m JsonCodeMap,
875				offset: JsonCodeMapOffset,
876				last_index: usize
877			}
878
879			impl<$lft, 'm> Iterator for $id<$lft, 'm> {
880				type Item = $item;
881
882				fn next(&mut $self) -> Option<Self::Item> {
883					$self.indexes.next().map(|$index| {
884						while $self.last_index < $index {
885							$self.last_index += 1;
886							$self.offset += 2 + $self.code_map.get($self.offset+2).unwrap().volume;
887						}
888
889						$e
890					})
891				}
892			}
893		)*
894	};
895}
896
897mapped_entries_iter! {
898	GetMappedEntries<'a> {
899		type Item = MappedEntryRef<'a>;
900
901		fn next(&mut self, index) {
902			mapped_entry_ref(entry_ref(&self.object.entries()[index]), self.offset, self.offset+1, self.offset+2)
903		}
904	}
905
906	GetIndexedMappedEntries<'a> {
907		type Item = (usize, MappedEntryRef<'a>);
908
909		fn next(&mut self, index) {
910			(
911				index,
912				mapped_entry_ref(entry_ref(&self.object.entries()[index]), self.offset, self.offset+1, self.offset+2)
913			)
914		}
915	}
916
917	GetMapped<'a> {
918		type Item = JsonMapped<&'a JsonValue>;
919
920		fn next(&mut self, index) {
921			JsonMapped(
922				&self.object.entries()[index].1,
923				self.offset+2,
924			)
925		}
926	}
927
928	GetIndexedMapped<'a> {
929		type Item = (usize, JsonMapped<&'a JsonValue>);
930
931		fn next(&mut self, index) {
932			(
933				index,
934				JsonMapped(
935					&self.object.entries()[index].1,
936					self.offset+2
937				)
938			)
939		}
940	}
941}
942
943impl JsonBorrowLexical for JsonObject {}
944
945impl JsonLexicalPartialEq for JsonObject {
946	fn lexical_eq(&self, other: &Self) -> bool {
947		self.map.as_entries().eq(other.map.as_entries())
948	}
949}
950
951impl JsonLexicalEq for JsonObject {}
952
953impl JsonLexicalHash for JsonObject {
954	fn lexical_hash<H: Hasher>(&self, state: &mut H) {
955		self.map.as_entries().hash(state)
956	}
957}
958
959impl fmt::Debug for JsonObject {
960	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
961		f.debug_map().entries(self.map.iter()).finish()
962	}
963}
964
965impl From<Vec<Entry>> for JsonObject {
966	fn from(entries: Vec<Entry>) -> Self {
967		Self::from_vec(entries)
968	}
969}
970
971impl<'a> IntoIterator for &'a JsonObject {
972	type Item = EntryRef<'a>;
973	type IntoIter = Iter<'a>;
974
975	fn into_iter(self) -> Self::IntoIter {
976		self.iter()
977	}
978}
979
980impl<'a> IntoIterator for &'a mut JsonObject {
981	type Item = (&'a Key, &'a mut JsonValue);
982	type IntoIter = IterMut<'a>;
983
984	fn into_iter(self) -> Self::IntoIter {
985		self.iter_mut()
986	}
987}
988
989impl IntoIterator for JsonObject {
990	type Item = Entry;
991	type IntoIter = std::vec::IntoIter<Entry>;
992
993	fn into_iter(self) -> Self::IntoIter {
994		self.map.into_iter()
995	}
996}
997
998impl Extend<Entry> for JsonObject {
999	fn extend<I: IntoIterator<Item = Entry>>(&mut self, iter: I) {
1000		for entry in iter {
1001			self.push_entry_back(entry);
1002		}
1003	}
1004}
1005
1006impl FromIterator<Entry> for JsonObject {
1007	fn from_iter<I: IntoIterator<Item = Entry>>(iter: I) -> Self {
1008		let mut object = JsonObject::default();
1009		object.extend(iter);
1010		object
1011	}
1012}
1013
1014/// Duplicate entry error.
1015#[derive(Debug)]
1016pub struct DuplicateEntry<T = Entry>(pub Box<T>, pub Box<T>);
1017
1018impl<T> DuplicateEntry<T> {
1019	pub fn new(a: T, b: T) -> Self {
1020		Self(Box::new(a), Box::new(b))
1021	}
1022}
1023
1024impl fmt::Display for DuplicateEntry {
1025	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1026		write!(f, "duplicate entry `{}`", self.0.0)
1027	}
1028}
1029
1030pub type DuplicateEntryRef<'a> = DuplicateEntry<EntryRef<'a>>;
1031
1032impl std::error::Error for DuplicateEntry {}
1033
1034#[cfg(test)]
1035mod tests {
1036	use crate::lexical::JsonBorrowLexical;
1037
1038	use super::*;
1039
1040	#[test]
1041	fn remove() {
1042		let mut object = JsonObject::new();
1043		object.insert("a", JsonValue::Null);
1044
1045		object.remove("a");
1046		object.remove("a");
1047	}
1048
1049	#[test]
1050	fn unordered_eq1() {
1051		let mut a = JsonObject::new();
1052		a.push_back("a", JsonValue::Null);
1053		a.push_back("b", JsonValue::Null);
1054
1055		let mut b = JsonObject::new();
1056		b.push_back("b", JsonValue::Null);
1057		b.push_back("a", JsonValue::Null);
1058
1059		assert_eq!(a, b);
1060		assert_ne!(a.as_lexical(), b.as_lexical())
1061	}
1062
1063	#[test]
1064	fn unordered_eq2() {
1065		let mut a = JsonObject::new();
1066		a.push_back("a", JsonValue::Null);
1067		a.push_back("a", JsonValue::Null);
1068
1069		let mut b = JsonObject::new();
1070		b.push_back("a", JsonValue::Null);
1071		b.push_back("a", JsonValue::Null);
1072
1073		assert_eq!(a, b);
1074		assert_eq!(a.as_lexical(), b.as_lexical())
1075	}
1076
1077	#[test]
1078	fn insert_front1() {
1079		let mut a = JsonObject::new();
1080		a.push_back("a", JsonValue::Null);
1081		a.push_back("b", JsonValue::Null);
1082		a.push_back("c", JsonValue::Null);
1083		a.shift_insert_front("b", JsonValue::Null);
1084
1085		let mut b = JsonObject::new();
1086		b.push_back("b", JsonValue::Null);
1087		b.push_back("a", JsonValue::Null);
1088		b.push_back("c", JsonValue::Null);
1089
1090		assert_eq!(a, b);
1091	}
1092
1093	#[test]
1094	fn insert_front2() {
1095		let mut a = JsonObject::new();
1096		a.push_back("a", JsonValue::Null);
1097		a.push_back("a", JsonValue::Null);
1098		a.push_back("c", JsonValue::Null);
1099		a.shift_insert_front("a", JsonValue::Null);
1100
1101		let mut b = JsonObject::new();
1102		b.push_back("a", JsonValue::Null);
1103		b.push_back("c", JsonValue::Null);
1104
1105		assert_eq!(a, b);
1106	}
1107
1108	#[test]
1109	fn mapped_entries() {
1110		use crate::JsonParse;
1111		let (json, code_map) = crate::JsonValue::parse_str(
1112			r#"{ "0": [null, null], "1": { "foo": 0, "bar": 1 }, "0": null }"#,
1113		)
1114		.unwrap();
1115		let object = json.into_object().unwrap();
1116
1117		let offsets: Vec<_> = object
1118			.get_mapped_entries(&code_map, 0, "0")
1119			.map(|JsonMapped((key, value), offset)| (offset, key.offset(), value.offset()))
1120			.collect();
1121
1122		assert_eq!(offsets, [(1, 2, 3), (15, 16, 17)]);
1123
1124		let offsets: Vec<_> = object
1125			.get_mapped_entries(&code_map, 0, "1")
1126			.map(|JsonMapped((key, value), offset)| (offset, key.offset(), value.offset()))
1127			.collect();
1128
1129		assert_eq!(offsets, [(6, 7, 8)]);
1130
1131		let offsets: Vec<_> = object
1132			.iter_mapped(&code_map, 0)
1133			.map(|JsonMapped((key, value), offset)| (offset, key.offset(), value.offset()))
1134			.collect();
1135
1136		assert_eq!(offsets, [(1, 2, 3), (6, 7, 8), (15, 16, 17)]);
1137	}
1138}