json_syntax/object/
mod.rs

1use crate::code_map::Mapped;
2use crate::{CodeMap, FragmentRef, UnorderedEq, UnorderedPartialEq, Value};
3use core::cmp::Ordering;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6
7mod index_map;
8
9pub use index_map::Equivalent;
10use index_map::IndexMap;
11
12/// Object key stack capacity.
13///
14/// If the key is longer than this value,
15/// it will be stored on the heap.
16pub const KEY_CAPACITY: usize = 16;
17
18/// Object key.
19pub type Key = smallstr::SmallString<[u8; KEY_CAPACITY]>;
20
21/// Object entry.
22#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
23pub struct Entry<K = Key, V = Value> {
24	pub key: K,
25	pub value: V,
26}
27
28impl<K, V> Entry<K, V> {
29	pub fn new(key: K, value: V) -> Self {
30		Self { key, value }
31	}
32
33	pub fn as_key(&self) -> &K {
34		&self.key
35	}
36
37	pub fn as_value(&self) -> &V {
38		&self.value
39	}
40
41	pub fn into_key(self) -> K {
42		self.key
43	}
44
45	pub fn into_value(self) -> V {
46		self.value
47	}
48
49	pub fn as_pair(&self) -> (&K, &V) {
50		(&self.key, &self.value)
51	}
52
53	pub fn into_pair(self) -> (K, V) {
54		(self.key, self.value)
55	}
56
57	pub fn as_ref(&self) -> Entry<&K, &V> {
58		Entry::new(&self.key, &self.value)
59	}
60
61	pub fn into_mapped(
62		self,
63		key_offset: usize,
64		value_offset: usize,
65	) -> Entry<Mapped<K>, Mapped<V>> {
66		Entry::new(
67			Mapped::new(key_offset, self.key),
68			Mapped::new(value_offset, self.value),
69		)
70	}
71}
72
73impl Entry {
74	pub fn get_fragment(&self, index: usize) -> Result<FragmentRef, usize> {
75		match index {
76			0 => Ok(FragmentRef::Entry(self)),
77			1 => Ok(FragmentRef::Key(&self.key)),
78			_ => self.value.get_fragment(index - 2),
79		}
80	}
81}
82
83pub type MappedEntry<'a> = Mapped<Entry<Mapped<&'a Key>, Mapped<&'a Value>>>;
84
85pub type IndexedMappedEntry<'a> = (usize, MappedEntry<'a>);
86
87pub type IndexedMappedValue<'a> = (usize, Mapped<&'a Value>);
88
89/// Object.
90#[derive(Clone)]
91pub struct Object {
92	/// The entries of the object, in order.
93	entries: Vec<Entry>,
94
95	/// Maps each key to an entry index.
96	indexes: IndexMap,
97}
98
99impl Default for Object {
100	fn default() -> Self {
101		Self {
102			entries: Vec::new(),
103			indexes: IndexMap::new(),
104		}
105	}
106}
107
108impl Object {
109	pub fn new() -> Self {
110		Self::default()
111	}
112
113	pub fn from_vec(entries: Vec<Entry>) -> Self {
114		let mut indexes = IndexMap::new();
115		for i in 0..entries.len() {
116			indexes.insert(&entries, i);
117		}
118
119		Self { entries, indexes }
120	}
121
122	pub fn capacity(&self) -> usize {
123		self.entries.capacity()
124	}
125
126	pub fn len(&self) -> usize {
127		self.entries.len()
128	}
129
130	pub fn is_empty(&self) -> bool {
131		self.entries.is_empty()
132	}
133
134	pub fn get_fragment(&self, mut index: usize) -> Result<FragmentRef, usize> {
135		for e in &self.entries {
136			match e.get_fragment(index) {
137				Ok(value) => return Ok(value),
138				Err(i) => index = i,
139			}
140		}
141
142		Err(index)
143	}
144
145	pub fn entries(&self) -> &[Entry] {
146		&self.entries
147	}
148
149	pub fn iter(&self) -> Iter {
150		self.entries.iter()
151	}
152
153	pub fn iter_mut(&mut self) -> IterMut {
154		IterMut(self.entries.iter_mut())
155	}
156
157	pub fn iter_mapped<'m>(&self, code_map: &'m CodeMap, offset: usize) -> IterMapped<'_, 'm> {
158		IterMapped {
159			entries: self.entries.iter(),
160			code_map,
161			offset: offset + 1,
162		}
163	}
164
165	/// Checks if this object contains the given key.
166	///
167	/// Runs in `O(1)` (average).
168	pub fn contains_key<Q>(&self, key: &Q) -> bool
169	where
170		Q: ?Sized + Hash + Equivalent<Key>,
171	{
172		self.indexes.get(&self.entries, key).is_some()
173	}
174
175	/// Returns an iterator over the values matching the given key.
176	///
177	/// Runs in `O(1)` (average).
178	pub fn get<Q>(&self, key: &Q) -> Values
179	where
180		Q: ?Sized + Hash + Equivalent<Key>,
181	{
182		let indexes = self
183			.indexes
184			.get(&self.entries, key)
185			.map(IntoIterator::into_iter)
186			.unwrap_or_default();
187		Values {
188			indexes,
189			object: self,
190		}
191	}
192
193	/// Returns an iterator over the values matching the given key.
194	///
195	/// Runs in `O(1)` (average).
196	pub fn get_mut<Q>(&mut self, key: &Q) -> ValuesMut
197	where
198		Q: ?Sized + Hash + Equivalent<Key>,
199	{
200		let indexes = self
201			.indexes
202			.get(&self.entries, key)
203			.map(IntoIterator::into_iter)
204			.unwrap_or_default();
205		ValuesMut {
206			indexes,
207			entries: &mut self.entries,
208		}
209	}
210
211	/// Returns the unique entry value matching the given key.
212	///
213	/// Returns an error if multiple entries match the key.
214	///
215	/// Runs in `O(1)` (average).
216	pub fn get_unique<Q>(&self, key: &Q) -> Result<Option<&Value>, Duplicate<&Entry>>
217	where
218		Q: ?Sized + Hash + Equivalent<Key>,
219	{
220		let mut entries = self.get_entries(key);
221
222		match entries.next() {
223			Some(entry) => match entries.next() {
224				Some(duplicate) => Err(Duplicate(entry, duplicate)),
225				None => Ok(Some(&entry.value)),
226			},
227			None => Ok(None),
228		}
229	}
230
231	/// Returns the unique entry value matching the given key.
232	///
233	/// Returns an error if multiple entries match the key.
234	///
235	/// Runs in `O(1)` (average).
236	pub fn get_unique_mut<Q>(&mut self, key: &Q) -> Result<Option<&mut Value>, Duplicate<&Entry>>
237	where
238		Q: ?Sized + Hash + Equivalent<Key>,
239	{
240		let index = {
241			let mut entries = self.get_entries_with_index(key);
242			match entries.next() {
243				Some((i, _)) => match entries.next() {
244					Some((j, _)) => Err(Duplicate(i, j)),
245					None => Ok(Some(i)),
246				},
247				None => Ok(None),
248			}
249		};
250
251		match index {
252			Ok(Some(i)) => Ok(Some(&mut self.entries[i].value)),
253			Ok(None) => Ok(None),
254			Err(Duplicate(i, j)) => Err(Duplicate(&self.entries[i], &self.entries[j])),
255		}
256	}
257
258	/// Returns an iterator over the entries matching the given key.
259	///
260	/// Runs in `O(1)` (average).
261	pub fn get_entries<Q>(&self, key: &Q) -> Entries
262	where
263		Q: ?Sized + Hash + Equivalent<Key>,
264	{
265		let indexes = self
266			.indexes
267			.get(&self.entries, key)
268			.map(IntoIterator::into_iter)
269			.unwrap_or_default();
270		Entries {
271			indexes,
272			object: self,
273		}
274	}
275
276	/// Returns the unique entry matching the given key.
277	///
278	/// Returns an error if multiple entries match the key.
279	///
280	/// Runs in `O(1)` (average).
281	pub fn get_unique_entry<Q>(&self, key: &Q) -> Result<Option<&Entry>, Duplicate<&Entry>>
282	where
283		Q: ?Sized + Hash + Equivalent<Key>,
284	{
285		let mut entries = self.get_entries(key);
286
287		match entries.next() {
288			Some(entry) => match entries.next() {
289				Some(duplicate) => Err(Duplicate(entry, duplicate)),
290				None => Ok(Some(entry)),
291			},
292			None => Ok(None),
293		}
294	}
295
296	/// Returns an iterator over the values matching the given key.
297	///
298	/// Runs in `O(1)` (average).
299	pub fn get_with_index<Q>(&self, key: &Q) -> ValuesWithIndex
300	where
301		Q: ?Sized + Hash + Equivalent<Key>,
302	{
303		let indexes = self
304			.indexes
305			.get(&self.entries, key)
306			.map(IntoIterator::into_iter)
307			.unwrap_or_default();
308		ValuesWithIndex {
309			indexes,
310			object: self,
311		}
312	}
313
314	/// Returns an iterator over the entries matching the given key.
315	///
316	/// Runs in `O(1)` (average).
317	pub fn get_entries_with_index<Q>(&self, key: &Q) -> EntriesWithIndex
318	where
319		Q: ?Sized + Hash + Equivalent<Key>,
320	{
321		let indexes = self
322			.indexes
323			.get(&self.entries, key)
324			.map(IntoIterator::into_iter)
325			.unwrap_or_default();
326		EntriesWithIndex {
327			indexes,
328			object: self,
329		}
330	}
331
332	/// Returns the (first) value associated to `key`, or insert a `key`-`value`
333	/// entry where `value` is returned by the given function `f`.
334	pub fn get_or_insert_with<Q>(&mut self, key: &Q, f: impl FnOnce() -> Value) -> &Value
335	where
336		Q: ?Sized + Hash + Equivalent<Key> + ToOwned,
337		Q::Owned: Into<Key>,
338	{
339		let index = match self.index_of(key) {
340			Some(index) => index,
341			None => {
342				let index = self.entries.len();
343				self.push(key.to_owned().into(), f());
344				index
345			}
346		};
347
348		&self.entries[index].value
349	}
350
351	/// Returns a mutable reference to the (first) value associated to `key`, or
352	/// insert a `key`-`value` entry where `value` is returned by the given
353	/// function `f`.
354	pub fn get_mut_or_insert_with<Q>(&mut self, key: &Q, f: impl FnOnce() -> Value) -> &mut Value
355	where
356		Q: ?Sized + Hash + Equivalent<Key> + ToOwned,
357		Q::Owned: Into<Key>,
358	{
359		let index = match self.index_of(key) {
360			Some(index) => index,
361			None => {
362				let index = self.entries.len();
363				self.push(key.to_owned().into(), f());
364				index
365			}
366		};
367
368		&mut self.entries[index].value
369	}
370
371	pub fn index_of<Q>(&self, key: &Q) -> Option<usize>
372	where
373		Q: ?Sized + Hash + Equivalent<Key>,
374	{
375		self.indexes
376			.get(&self.entries, key)
377			.map(index_map::Indexes::first)
378	}
379
380	pub fn redundant_index_of<Q>(&self, key: &Q) -> Option<usize>
381	where
382		Q: ?Sized + Hash + Equivalent<Key>,
383	{
384		self.indexes
385			.get(&self.entries, key)
386			.and_then(index_map::Indexes::redundant)
387	}
388
389	pub fn indexes_of<Q>(&self, key: &Q) -> Indexes
390	where
391		Q: ?Sized + Hash + Equivalent<Key>,
392	{
393		self.indexes
394			.get(&self.entries, key)
395			.map(IntoIterator::into_iter)
396			.unwrap_or_default()
397	}
398
399	/// Returns an iterator over the mapped entries matching the given key.
400	///
401	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
402	/// the entry fragment offset.
403	pub fn get_mapped_entries<'m, Q>(
404		&self,
405		code_map: &'m CodeMap,
406		offset: usize,
407		key: &Q,
408	) -> MappedEntries<'_, 'm>
409	where
410		Q: ?Sized + Hash + Equivalent<Key>,
411	{
412		let indexes = self
413			.indexes
414			.get(&self.entries, key)
415			.map(IntoIterator::into_iter)
416			.unwrap_or_default();
417		MappedEntries {
418			indexes,
419			object: self,
420			code_map,
421			offset: offset + 1,
422			last_index: 0,
423		}
424	}
425
426	/// Returns the unique mapped entry matching the given key.
427	///
428	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
429	/// the entry fragment offset.
430	pub fn get_unique_mapped_entry<Q>(
431		&self,
432		code_map: &CodeMap,
433		offset: usize,
434		key: &Q,
435	) -> Result<Option<MappedEntry>, Duplicate<MappedEntry>>
436	where
437		Q: ?Sized + Hash + Equivalent<Key>,
438	{
439		let mut entries = self.get_mapped_entries(code_map, offset, key);
440
441		match entries.next() {
442			Some(entry) => match entries.next() {
443				Some(duplicate) => Err(Duplicate(entry, duplicate)),
444				None => Ok(Some(entry)),
445			},
446			None => Ok(None),
447		}
448	}
449
450	/// Returns an iterator over the mapped entries matching the given key, with
451	/// their index.
452	///
453	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
454	/// the entry fragment offset.
455	pub fn get_mapped_entries_with_index<'m, Q>(
456		&self,
457		code_map: &'m CodeMap,
458		offset: usize,
459		key: &Q,
460	) -> MappedEntriesWithIndex<'_, 'm>
461	where
462		Q: ?Sized + Hash + Equivalent<Key>,
463	{
464		let indexes = self
465			.indexes
466			.get(&self.entries, key)
467			.map(IntoIterator::into_iter)
468			.unwrap_or_default();
469		MappedEntriesWithIndex {
470			indexes,
471			object: self,
472			code_map,
473			offset: offset + 1,
474			last_index: 0,
475		}
476	}
477
478	/// Returns the unique mapped entry matching the given key, with its index.
479	///
480	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
481	/// the entry fragment offset.
482	pub fn get_unique_mapped_entry_with_index<Q>(
483		&self,
484		code_map: &CodeMap,
485		offset: usize,
486		key: &Q,
487	) -> Result<Option<IndexedMappedEntry>, Duplicate<IndexedMappedEntry>>
488	where
489		Q: ?Sized + Hash + Equivalent<Key>,
490	{
491		let mut entries = self.get_mapped_entries_with_index(code_map, offset, key);
492
493		match entries.next() {
494			Some(entry) => match entries.next() {
495				Some(duplicate) => Err(Duplicate(entry, duplicate)),
496				None => Ok(Some(entry)),
497			},
498			None => Ok(None),
499		}
500	}
501
502	/// Returns an iterator over the mapped values matching the given key.
503	///
504	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
505	/// the entry fragment offset.
506	pub fn get_mapped<'m, Q>(
507		&self,
508		code_map: &'m CodeMap,
509		offset: usize,
510		key: &Q,
511	) -> MappedValues<'_, 'm>
512	where
513		Q: ?Sized + Hash + Equivalent<Key>,
514	{
515		let indexes = self
516			.indexes
517			.get(&self.entries, key)
518			.map(IntoIterator::into_iter)
519			.unwrap_or_default();
520		MappedValues {
521			indexes,
522			object: self,
523			code_map,
524			offset: offset + 1,
525			last_index: 0,
526		}
527	}
528
529	/// Returns the unique mapped values matching the given key.
530	///
531	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
532	/// the entry fragment offset.
533	pub fn get_unique_mapped<Q>(
534		&self,
535		code_map: &CodeMap,
536		offset: usize,
537		key: &Q,
538	) -> Result<Option<Mapped<&Value>>, Duplicate<Mapped<&Value>>>
539	where
540		Q: ?Sized + Hash + Equivalent<Key>,
541	{
542		let mut entries = self.get_mapped(code_map, offset, key);
543
544		match entries.next() {
545			Some(entry) => match entries.next() {
546				Some(duplicate) => Err(Duplicate(entry, duplicate)),
547				None => Ok(Some(entry)),
548			},
549			None => Ok(None),
550		}
551	}
552
553	/// Returns an iterator over the mapped values matching the given key, with
554	/// their index.
555	///
556	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
557	/// the entry fragment offset.
558	pub fn get_mapped_with_index<'m, Q>(
559		&self,
560		code_map: &'m CodeMap,
561		offset: usize,
562		key: &Q,
563	) -> MappedValuesWithIndex<'_, 'm>
564	where
565		Q: ?Sized + Hash + Equivalent<Key>,
566	{
567		let indexes = self
568			.indexes
569			.get(&self.entries, key)
570			.map(IntoIterator::into_iter)
571			.unwrap_or_default();
572		MappedValuesWithIndex {
573			indexes,
574			object: self,
575			code_map,
576			offset: offset + 1,
577			last_index: 0,
578		}
579	}
580
581	/// Returns the unique mapped values matching the given key, with its index.
582	///
583	/// Runs in `O(n)` (average). `O(1)` to find the entry, `O(n)` to compute
584	/// the entry fragment offset.
585	pub fn get_unique_mapped_with_index<Q>(
586		&self,
587		code_map: &CodeMap,
588		offset: usize,
589		key: &Q,
590	) -> Result<Option<IndexedMappedValue>, Duplicate<IndexedMappedValue>>
591	where
592		Q: ?Sized + Hash + Equivalent<Key>,
593	{
594		let mut entries = self.get_mapped_with_index(code_map, offset, key);
595
596		match entries.next() {
597			Some(entry) => match entries.next() {
598				Some(duplicate) => Err(Duplicate(entry, duplicate)),
599				None => Ok(Some(entry)),
600			},
601			None => Ok(None),
602		}
603	}
604
605	pub fn first(&self) -> Option<&Entry> {
606		self.entries.first()
607	}
608
609	pub fn last(&self) -> Option<&Entry> {
610		self.entries.last()
611	}
612
613	/// Push the given key-value pair to the end of the object.
614	///
615	/// Returns `true` if the key was not already present in the object,
616	/// and `false` otherwise.
617	/// Any previous entry matching the key is **not** overridden: duplicates
618	/// are preserved, in order.
619	///
620	/// Runs in `O(1)`.
621	pub fn push(&mut self, key: Key, value: Value) -> bool {
622		self.push_entry(Entry::new(key, value))
623	}
624
625	pub fn push_entry(&mut self, entry: Entry) -> bool {
626		let index = self.entries.len();
627		self.entries.push(entry);
628		self.indexes.insert(&self.entries, index)
629	}
630
631	/// Push the given key-value pair to the top of the object.
632	///
633	/// Returns `true` if the key was not already present in the object,
634	/// and `false` otherwise.
635	/// Any previous entry matching the key is **not** overridden: duplicates
636	/// are preserved, in order.
637	///
638	/// Runs in `O(n)`.
639	pub fn push_front(&mut self, key: Key, value: Value) -> bool {
640		self.push_entry_front(Entry::new(key, value))
641	}
642
643	pub fn push_entry_front(&mut self, entry: Entry) -> bool {
644		self.entries.insert(0, entry);
645		self.indexes.shift_up(0);
646		self.indexes.insert(&self.entries, 0)
647	}
648
649	/// Removes the entry at the given index.
650	pub fn remove_at(&mut self, index: usize) -> Option<Entry> {
651		if index < self.entries.len() {
652			self.indexes.remove(&self.entries, index);
653			self.indexes.shift_down(index);
654			Some(self.entries.remove(index))
655		} else {
656			None
657		}
658	}
659
660	/// Inserts the given key-value pair.
661	///
662	/// If one or more entries are already matching the given key,
663	/// all of them are removed and returned in the resulting iterator.
664	/// Otherwise, `None` is returned.
665	pub fn insert(&mut self, key: Key, value: Value) -> Option<RemovedByInsertion> {
666		match self.index_of(&key) {
667			Some(index) => {
668				let mut entry = Entry::new(key, value);
669				core::mem::swap(&mut entry, &mut self.entries[index]);
670				Some(RemovedByInsertion {
671					index,
672					first: Some(entry),
673					object: self,
674				})
675			}
676			None => {
677				self.push(key, value);
678				None
679			}
680		}
681	}
682
683	/// Inserts the given key-value pair on top of the object.
684	///
685	/// If one or more entries are already matching the given key,
686	/// all of them are removed and returned in the resulting iterator.
687	pub fn insert_front(&mut self, key: Key, value: Value) -> RemovedByInsertFront {
688		if let Some(first) = self.entries.first_mut() {
689			if first.key == key {
690				let first = core::mem::replace(first, Entry::new(key, value));
691				return RemovedByInsertFront {
692					first: Some(first),
693					object: self,
694				};
695			}
696		}
697
698		self.push_front(key, value);
699		RemovedByInsertFront {
700			first: None,
701			object: self,
702		}
703	}
704
705	/// Remove all entries associated to the given key.
706	///
707	/// Runs in `O(n)` time (average).
708	pub fn remove<'q, Q>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, Q>
709	where
710		Q: ?Sized + Hash + Equivalent<Key>,
711	{
712		RemovedEntries { key, object: self }
713	}
714
715	/// Remove the unique entry associated to the given key.
716	///
717	/// Returns an error if multiple entries match the key.
718	///
719	/// Runs in `O(n)` time (average).
720	pub fn remove_unique<Q>(&mut self, key: &Q) -> Result<Option<Entry>, Duplicate<Entry>>
721	where
722		Q: ?Sized + Hash + Equivalent<Key>,
723	{
724		let mut entries = self.remove(key);
725
726		match entries.next() {
727			Some(entry) => match entries.next() {
728				Some(duplicate) => Err(Duplicate(entry, duplicate)),
729				None => Ok(Some(entry)),
730			},
731			None => Ok(None),
732		}
733	}
734
735	/// Sort the entries by key name.
736	///
737	/// Entries with the same key are sorted by value.
738	pub fn sort(&mut self) {
739		use locspan::BorrowStripped;
740		self.entries.sort_by(|a, b| a.stripped().cmp(b.stripped()));
741		self.indexes.clear();
742
743		for i in 0..self.entries.len() {
744			self.indexes.insert(&self.entries, i);
745		}
746	}
747
748	/// Puts this JSON object in canonical form according to
749	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
750	///
751	/// This will canonicalize the entries and sort them by key.
752	/// Entries with the same key are sorted by value.
753	#[cfg(feature = "canonicalize")]
754	pub fn canonicalize_with(&mut self, buffer: &mut ryu_js::Buffer) {
755		for (_, item) in self.iter_mut() {
756			item.canonicalize_with(buffer);
757		}
758
759		self.sort()
760	}
761
762	/// Puts this JSON object in canonical form according to
763	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
764	#[cfg(feature = "canonicalize")]
765	pub fn canonicalize(&mut self) {
766		let mut buffer = ryu_js::Buffer::new();
767		self.canonicalize_with(&mut buffer)
768	}
769}
770
771pub type Iter<'a> = core::slice::Iter<'a, Entry>;
772
773pub struct IterMut<'a>(std::slice::IterMut<'a, Entry>);
774
775impl<'a> Iterator for IterMut<'a> {
776	type Item = (&'a Key, &'a mut Value);
777
778	fn next(&mut self) -> Option<Self::Item> {
779		self.0.next().map(|entry| (&entry.key, &mut entry.value))
780	}
781}
782
783pub struct IterMapped<'a, 'm> {
784	entries: std::slice::Iter<'a, Entry>,
785	code_map: &'m CodeMap,
786	offset: usize,
787}
788
789impl<'a, 'm> Iterator for IterMapped<'a, 'm> {
790	type Item = MappedEntry<'a>;
791
792	fn next(&mut self) -> Option<Self::Item> {
793		self.entries.next().map(|e| {
794			let offset = self.offset;
795			self.offset += 2 + self.code_map.get(self.offset + 2).unwrap().volume;
796			Mapped::new(offset, e.as_ref().into_mapped(offset + 1, offset + 2))
797		})
798	}
799}
800
801impl PartialEq for Object {
802	fn eq(&self, other: &Self) -> bool {
803		self.entries == other.entries
804	}
805}
806
807impl Eq for Object {}
808
809impl UnorderedPartialEq for Object {
810	fn unordered_eq(&self, other: &Self) -> bool {
811		if self.entries.len() != other.entries.len() {
812			return false;
813		}
814
815		if !self.iter().all(|Entry { key, value: a }| {
816			other
817				.get_entries(key)
818				.any(|Entry { value: b, .. }| a.unordered_eq(b))
819		}) {
820			return false;
821		}
822
823		if self.indexes.contains_duplicate_keys()
824			&& !other.iter().all(
825				|Entry {
826				     key: other_key,
827				     value: b,
828				 }| {
829					self.get_entries(other_key)
830						.any(|Entry { value: a, .. }| a.unordered_eq(b))
831				},
832			) {
833			return false;
834		}
835
836		true
837	}
838}
839
840impl UnorderedEq for Object {}
841
842impl PartialOrd for Object {
843	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
844		Some(self.entries.cmp(&other.entries))
845	}
846}
847
848impl Ord for Object {
849	fn cmp(&self, other: &Self) -> Ordering {
850		self.entries.cmp(&other.entries)
851	}
852}
853
854impl Hash for Object {
855	fn hash<H: Hasher>(&self, state: &mut H) {
856		self.entries.hash(state)
857	}
858}
859
860impl fmt::Debug for Object {
861	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
862		f.debug_map()
863			.entries(self.entries.iter().map(Entry::as_pair))
864			.finish()
865	}
866}
867
868impl From<Vec<Entry>> for Object {
869	fn from(entries: Vec<Entry>) -> Self {
870		Self::from_vec(entries)
871	}
872}
873
874impl<'a> IntoIterator for &'a Object {
875	type Item = &'a Entry;
876	type IntoIter = core::slice::Iter<'a, Entry>;
877
878	fn into_iter(self) -> Self::IntoIter {
879		self.iter()
880	}
881}
882
883impl<'a> IntoIterator for &'a mut Object {
884	type Item = (&'a Key, &'a mut Value);
885	type IntoIter = IterMut<'a>;
886
887	fn into_iter(self) -> Self::IntoIter {
888		self.iter_mut()
889	}
890}
891
892impl IntoIterator for Object {
893	type Item = Entry;
894	type IntoIter = std::vec::IntoIter<Entry>;
895
896	fn into_iter(self) -> Self::IntoIter {
897		self.entries.into_iter()
898	}
899}
900
901impl Extend<Entry> for Object {
902	fn extend<I: IntoIterator<Item = Entry>>(&mut self, iter: I) {
903		for entry in iter {
904			self.push_entry(entry);
905		}
906	}
907}
908
909impl FromIterator<Entry> for Object {
910	fn from_iter<I: IntoIterator<Item = Entry>>(iter: I) -> Self {
911		let mut object = Object::default();
912		object.extend(iter);
913		object
914	}
915}
916
917impl Extend<(Key, Value)> for Object {
918	fn extend<I: IntoIterator<Item = (Key, Value)>>(&mut self, iter: I) {
919		for (key, value) in iter {
920			self.push(key, value);
921		}
922	}
923}
924
925impl FromIterator<(Key, Value)> for Object {
926	fn from_iter<I: IntoIterator<Item = (Key, Value)>>(iter: I) -> Self {
927		let mut object = Object::default();
928		object.extend(iter);
929		object
930	}
931}
932
933pub enum Indexes<'a> {
934	Some {
935		first: Option<usize>,
936		other: core::slice::Iter<'a, usize>,
937	},
938	None,
939}
940
941impl<'a> Default for Indexes<'a> {
942	fn default() -> Self {
943		Self::None
944	}
945}
946
947impl<'a> Iterator for Indexes<'a> {
948	type Item = usize;
949
950	fn next(&mut self) -> Option<Self::Item> {
951		match self {
952			Self::Some { first, other } => match first.take() {
953				Some(index) => Some(index),
954				None => other.next().cloned(),
955			},
956			Self::None => None,
957		}
958	}
959}
960
961macro_rules! entries_iter {
962	($($id:ident <$lft:lifetime> {
963		type Item = $item:ty ;
964
965		fn next(&mut $self:ident, $index:ident) { $e:expr }
966	})*) => {
967		$(
968			pub struct $id<$lft> {
969				indexes: Indexes<$lft>,
970				object: &$lft Object
971			}
972
973			impl<$lft> Iterator for $id<$lft> {
974				type Item = $item;
975
976				fn next(&mut $self) -> Option<Self::Item> {
977					$self.indexes.next().map(|$index| $e)
978				}
979			}
980		)*
981	};
982}
983
984entries_iter! {
985	Values<'a> {
986		type Item = &'a Value;
987
988		fn next(&mut self, index) { &self.object.entries[index].value }
989	}
990
991	ValuesWithIndex<'a> {
992		type Item = (usize, &'a Value);
993
994		fn next(&mut self, index) { (index, &self.object.entries[index].value) }
995	}
996
997	Entries<'a> {
998		type Item = &'a Entry;
999
1000		fn next(&mut self, index) { &self.object.entries[index] }
1001	}
1002
1003	EntriesWithIndex<'a> {
1004		type Item = (usize, &'a Entry);
1005
1006		fn next(&mut self, index) { (index, &self.object.entries[index]) }
1007	}
1008}
1009
1010macro_rules! entries_iter_mut {
1011	($($id:ident <$lft:lifetime> {
1012		type Item = $item:ty ;
1013
1014		fn next(&mut $self:ident, $index:ident) { $e:expr }
1015	})*) => {
1016		$(
1017			pub struct $id<$lft> {
1018				indexes: Indexes<$lft>,
1019				entries: &$lft mut [Entry]
1020			}
1021
1022			impl<$lft> Iterator for $id<$lft> {
1023				type Item = $item;
1024
1025				fn next(&mut $self) -> Option<Self::Item> {
1026					$self.indexes.next().map(|$index| $e)
1027				}
1028			}
1029		)*
1030	};
1031}
1032
1033entries_iter_mut! {
1034	ValuesMut<'a> {
1035		type Item = &'a mut Value;
1036
1037		fn next(&mut self, index) {
1038			// This is safe because there is no aliasing between the values.
1039			unsafe { core::mem::transmute(&mut self.entries[index].value) }
1040		}
1041	}
1042
1043	ValuesMutWithIndex<'a> {
1044		type Item = (usize, &'a mut Value);
1045
1046		fn next(&mut self, index) {
1047			// This is safe because there is no aliasing between the values.
1048			unsafe { (index, core::mem::transmute::<&mut Value, &'a mut Value>(&mut self.entries[index].value)) }
1049		}
1050	}
1051}
1052
1053macro_rules! mapped_entries_iter {
1054	($($id:ident <$lft:lifetime> {
1055		type Item = $item:ty ;
1056
1057		fn next(&mut $self:ident, $index:ident) { $e:expr }
1058	})*) => {
1059		$(
1060			pub struct $id<$lft, 'm> {
1061				indexes: Indexes<$lft>,
1062				object: &$lft Object,
1063				code_map: &'m CodeMap,
1064				offset: usize,
1065				last_index: usize
1066			}
1067
1068			impl<$lft, 'm> Iterator for $id<$lft, 'm> {
1069				type Item = $item;
1070
1071				fn next(&mut $self) -> Option<Self::Item> {
1072					$self.indexes.next().map(|$index| {
1073						while $self.last_index < $index {
1074							$self.last_index += 1;
1075							$self.offset += 2 + $self.code_map.get($self.offset+2).unwrap().volume;
1076						}
1077
1078						$e
1079					})
1080				}
1081			}
1082		)*
1083	};
1084}
1085
1086mapped_entries_iter! {
1087	MappedEntries<'a> {
1088		type Item = MappedEntry<'a>;
1089
1090		fn next(&mut self, index) {
1091			Mapped::new(
1092				self.offset,
1093				self.object.entries[index].as_ref().into_mapped(
1094					self.offset+1,
1095					self.offset+2
1096				)
1097			)
1098		}
1099	}
1100
1101	MappedEntriesWithIndex<'a> {
1102		type Item = (usize, MappedEntry<'a>);
1103
1104		fn next(&mut self, index) {
1105			(
1106				index,
1107				Mapped::new(
1108					self.offset,
1109					self.object.entries[index].as_ref().into_mapped(
1110						self.offset+1,
1111						self.offset+2
1112					)
1113				)
1114			)
1115		}
1116	}
1117
1118	MappedValues<'a> {
1119		type Item = Mapped<&'a Value>;
1120
1121		fn next(&mut self, index) {
1122			Mapped::new(
1123				self.offset+2,
1124				&self.object.entries[index].value
1125			)
1126		}
1127	}
1128
1129	MappedValuesWithIndex<'a> {
1130		type Item = (usize, Mapped<&'a Value>);
1131
1132		fn next(&mut self, index) {
1133			(
1134				index,
1135				Mapped::new(
1136					self.offset+2,
1137					&self.object.entries[index].value
1138				)
1139			)
1140		}
1141	}
1142}
1143
1144pub struct RemovedByInsertion<'a> {
1145	index: usize,
1146	first: Option<Entry>,
1147	object: &'a mut Object,
1148}
1149
1150impl<'a> Iterator for RemovedByInsertion<'a> {
1151	type Item = Entry;
1152
1153	fn next(&mut self) -> Option<Self::Item> {
1154		match self.first.take() {
1155			Some(entry) => Some(entry),
1156			None => {
1157				let key = &self.object.entries[self.index].key;
1158				self.object
1159					.redundant_index_of(key)
1160					.and_then(|index| self.object.remove_at(index))
1161			}
1162		}
1163	}
1164}
1165
1166impl<'a> Drop for RemovedByInsertion<'a> {
1167	fn drop(&mut self) {
1168		self.last();
1169	}
1170}
1171
1172pub struct RemovedByInsertFront<'a> {
1173	first: Option<Entry>,
1174	object: &'a mut Object,
1175}
1176
1177impl<'a> Iterator for RemovedByInsertFront<'a> {
1178	type Item = Entry;
1179
1180	fn next(&mut self) -> Option<Self::Item> {
1181		match self.first.take() {
1182			Some(entry) => Some(entry),
1183			None => {
1184				let key = &self.object.entries[0].key;
1185				self.object
1186					.redundant_index_of(key)
1187					.and_then(|index| self.object.remove_at(index))
1188			}
1189		}
1190	}
1191}
1192
1193impl<'a> Drop for RemovedByInsertFront<'a> {
1194	fn drop(&mut self) {
1195		self.last();
1196	}
1197}
1198
1199pub struct RemovedEntries<'a, 'q, Q: ?Sized>
1200where
1201	Q: Hash + Equivalent<Key>,
1202{
1203	key: &'q Q,
1204	object: &'a mut Object,
1205}
1206
1207impl<'a, 'q, Q: ?Sized> Iterator for RemovedEntries<'a, 'q, Q>
1208where
1209	Q: Hash + Equivalent<Key>,
1210{
1211	type Item = Entry;
1212
1213	fn next(&mut self) -> Option<Self::Item> {
1214		self.object
1215			.index_of(self.key)
1216			.and_then(|index| self.object.remove_at(index))
1217	}
1218}
1219
1220impl<'a, 'q, Q: ?Sized> Drop for RemovedEntries<'a, 'q, Q>
1221where
1222	Q: Hash + Equivalent<Key>,
1223{
1224	fn drop(&mut self) {
1225		self.last();
1226	}
1227}
1228
1229#[derive(Debug)]
1230pub struct Duplicate<T>(pub T, pub T);
1231
1232/// Duplicate entry error.
1233pub type DuplicateEntry = Duplicate<Entry>;
1234
1235impl fmt::Display for DuplicateEntry {
1236	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237		write!(f, "duplicate entry `{}`", self.0.key)
1238	}
1239}
1240
1241impl std::error::Error for DuplicateEntry {}
1242
1243#[cfg(test)]
1244mod tests {
1245	use crate::BorrowUnordered;
1246
1247	use super::*;
1248
1249	#[test]
1250	fn remove() {
1251		let mut object = Object::new();
1252		object.insert("a".into(), Value::Null);
1253
1254		object.remove("a");
1255		object.remove("a");
1256	}
1257
1258	#[test]
1259	fn unordered_eq1() {
1260		let mut a = Object::new();
1261		a.push("a".into(), Value::Null);
1262		a.push("b".into(), Value::Null);
1263
1264		let mut b = Object::new();
1265		b.push("b".into(), Value::Null);
1266		b.push("a".into(), Value::Null);
1267
1268		assert_ne!(a, b);
1269		assert_eq!(a.as_unordered(), b.as_unordered())
1270	}
1271
1272	#[test]
1273	fn unordered_eq2() {
1274		let mut a = Object::new();
1275		a.push("a".into(), Value::Null);
1276		a.push("a".into(), Value::Null);
1277
1278		let mut b = Object::new();
1279		b.push("a".into(), Value::Null);
1280		b.push("a".into(), Value::Null);
1281
1282		assert_eq!(a, b);
1283		assert_eq!(a.as_unordered(), b.as_unordered())
1284	}
1285
1286	#[test]
1287	fn insert_front1() {
1288		let mut a = Object::new();
1289		a.push("a".into(), Value::Null);
1290		a.push("b".into(), Value::Null);
1291		a.push("c".into(), Value::Null);
1292		a.insert_front("b".into(), Value::Null);
1293
1294		let mut b = Object::new();
1295		b.push("b".into(), Value::Null);
1296		b.push("a".into(), Value::Null);
1297		b.push("c".into(), Value::Null);
1298
1299		assert_eq!(a, b);
1300	}
1301
1302	#[test]
1303	fn insert_front2() {
1304		let mut a = Object::new();
1305		a.push("a".into(), Value::Null);
1306		a.push("a".into(), Value::Null);
1307		a.push("c".into(), Value::Null);
1308		a.insert_front("a".into(), Value::Null);
1309
1310		let mut b = Object::new();
1311		b.push("a".into(), Value::Null);
1312		b.push("c".into(), Value::Null);
1313
1314		assert_eq!(a, b);
1315	}
1316
1317	#[test]
1318	fn mapped_entries() {
1319		use crate::Parse;
1320		let (json, code_map) = crate::Value::parse_str(
1321			r#"{ "0": [null, null], "1": { "foo": 0, "bar": 1 }, "0": null }"#,
1322		)
1323		.unwrap();
1324		let object = json.into_object().unwrap();
1325
1326		let offsets: Vec<_> = object
1327			.get_mapped_entries(&code_map, 0, "0")
1328			.map(|e| (e.offset, e.value.key.offset, e.value.value.offset))
1329			.collect();
1330
1331		assert_eq!(offsets, [(1, 2, 3), (15, 16, 17)]);
1332
1333		let offsets: Vec<_> = object
1334			.get_mapped_entries(&code_map, 0, "1")
1335			.map(|e| (e.offset, e.value.key.offset, e.value.value.offset))
1336			.collect();
1337
1338		assert_eq!(offsets, [(6, 7, 8)]);
1339
1340		let offsets: Vec<_> = object
1341			.iter_mapped(&code_map, 0)
1342			.map(|e| (e.offset, e.value.key.offset, e.value.value.offset))
1343			.collect();
1344
1345		assert_eq!(offsets, [(1, 2, 3), (6, 7, 8), (15, 16, 17)]);
1346	}
1347}