Struct json_syntax::object::Object

source ·
pub struct Object<M = ()> { /* private fields */ }
Expand description

Object.

Implementations§

Examples found in repository?
src/parse/value.rs (line 59)
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
	fn parse_spanned<C, F, E>(
		parser: &mut Parser<C, F, E>,
		context: Context,
	) -> Result<Meta<Self, Span>, Meta<Error<M, E>, M>>
	where
		C: Iterator<Item = Result<DecodedChar, E>>,
		F: FnMut(Span) -> M,
	{
		parser.skip_whitespaces()?;

		let value = match parser.peek_char()? {
			Some('n') => <()>::parse_spanned(parser, context)?.map(|()| Value::Null),
			Some('t' | 'f') => bool::parse_spanned(parser, context)?.map(Value::Boolean),
			Some('0'..='9' | '-') => NumberBuf::parse_spanned(parser, context)?.map(Value::Number),
			Some('"') => String::parse_spanned(parser, context)?.map(Value::String),
			Some('[') => match array::StartFragment::parse_spanned(parser, context)? {
				Meta(array::StartFragment::Empty, span) => Meta(Value::Array(Array::new()), span),
				Meta(array::StartFragment::NonEmpty, span) => {
					return Ok(Meta(Self::BeginArray, span))
				}
			},
			Some('{') => match object::StartFragment::parse_spanned(parser, context)? {
				Meta(object::StartFragment::Empty, span) => {
					Meta(Value::Object(Object::new()), span)
				}
				Meta(object::StartFragment::NonEmpty(key), span) => {
					return Ok(Meta(Self::BeginObject(key), span))
				}
			},
			unexpected => return Err(Meta(Error::unexpected(unexpected), parser.position.last())),
		};

		parser.skip_trailing_whitespaces(context)?;

		Ok(value.map(Self::Value))
	}
}

impl<M> Parse<M> for Value<M> {
	fn parse_spanned<C, F, E>(
		parser: &mut Parser<C, F, E>,
		context: Context,
	) -> Result<Meta<Self, Span>, Meta<Error<M, E>, M>>
	where
		C: Iterator<Item = Result<DecodedChar, E>>,
		F: FnMut(Span) -> M,
	{
		enum Item<M> {
			Array(Meta<Array<M>, Span>),
			ArrayItem(Meta<Array<M>, Span>),
			Object(Meta<Object<M>, Span>),
			ObjectEntry(Meta<Object<M>, Span>, Meta<Key, M>),
		}

		let mut stack: Vec<Item<M>> = vec![];
		let mut value: Option<Meta<Value<M>, Span>> = None;

		fn stack_context<M>(stack: &[Item<M>], root: Context) -> Context {
			match stack.last() {
				Some(Item::Array(_) | Item::ArrayItem(_)) => Context::Array,
				Some(Item::Object(_)) => Context::ObjectKey,
				Some(Item::ObjectEntry(_, _)) => Context::ObjectValue,
				None => root,
			}
		}

		loop {
			match stack.pop() {
				None => match Fragment::value_or_parse(
					value.take(),
					parser,
					stack_context(&stack, context),
				)? {
					Meta(Fragment::Value(value), span) => break Ok(Meta(value, span)),
					Meta(Fragment::BeginArray, span) => {
						stack.push(Item::ArrayItem(Meta(Array::new(), span)))
					}
					Meta(Fragment::BeginObject(key), span) => {
						stack.push(Item::ObjectEntry(Meta(Object::new(), span), key))
					}
				},
				Some(Item::Array(Meta(array, span))) => {
					match array::ContinueFragment::parse_spanned(
						parser,
						stack_context(&stack, context),
					)? {
						Meta(array::ContinueFragment::Item, comma_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(comma_span))))
						}
						Meta(array::ContinueFragment::End, closing_span) => {
							parser.skip_trailing_whitespaces(stack_context(&stack, context))?;
							value = Some(Meta(Value::Array(array), span.union(closing_span)))
						}
					}
				}
				Some(Item::ArrayItem(Meta(mut array, span))) => {
					match Fragment::value_or_parse(value.take(), parser, Context::Array)? {
						Meta(Fragment::Value(value), value_span) => {
							array.push(Meta(value, parser.position.metadata_at(value_span)));
							stack.push(Item::Array(Meta(array, span.union(value_span))));
						}
						Meta(Fragment::BeginArray, value_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(value_span))));
							stack.push(Item::ArrayItem(Meta(Array::new(), value_span)))
						}
						Meta(Fragment::BeginObject(value_key), value_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(value_span))));
							stack.push(Item::ObjectEntry(
								Meta(Object::new(), value_span),
								value_key,
							))
						}
					}
				}
				Some(Item::Object(Meta(object, span))) => {
					match object::ContinueFragment::parse_spanned(
						parser,
						stack_context(&stack, context),
					)? {
						Meta(object::ContinueFragment::Entry(key), comma_key_span) => stack.push(
							Item::ObjectEntry(Meta(object, span.union(comma_key_span)), key),
						),
						Meta(object::ContinueFragment::End, closing_span) => {
							parser.skip_trailing_whitespaces(stack_context(&stack, context))?;
							value = Some(Meta(Value::Object(object), span.union(closing_span)))
						}
					}
				}
				Some(Item::ObjectEntry(Meta(mut object, span), key)) => {
					match Fragment::value_or_parse(value.take(), parser, Context::ObjectValue)? {
						Meta(Fragment::Value(value), value_span) => {
							object.push(key, Meta(value, parser.position.metadata_at(value_span)));
							stack.push(Item::Object(Meta(object, span.union(value_span))));
						}
						Meta(Fragment::BeginArray, value_span) => {
							stack
								.push(Item::ObjectEntry(Meta(object, span.union(value_span)), key));
							stack.push(Item::ArrayItem(Meta(Array::new(), value_span)))
						}
						Meta(Fragment::BeginObject(value_key), value_span) => {
							stack
								.push(Item::ObjectEntry(Meta(object, span.union(value_span)), key));
							stack.push(Item::ObjectEntry(
								Meta(Object::new(), value_span),
								value_key,
							))
						}
					}
				}
			}
		}
	}
Examples found in repository?
src/object.rs (line 581)
580
581
582
	fn from(entries: Vec<Entry<M>>) -> Self {
		Self::from_vec(entries)
	}
Examples found in repository?
src/object.rs (line 488)
484
485
486
487
488
489
490
491
492
493
494
495
496
497
	pub fn try_map_metadata<N, E>(
		self,
		mut f: impl FnMut(M) -> Result<N, E>,
	) -> Result<Object<N>, E> {
		let mut entries = Vec::with_capacity(self.len());
		for entry in self.entries {
			entries.push(entry.try_map_metadata(&mut f)?)
		}

		Ok(Object {
			entries,
			indexes: self.indexes,
		})
	}
Examples found in repository?
src/lib.rs (line 271)
268
269
270
271
272
273
274
	pub fn is_empty_array_or_object(&self) -> bool {
		match self {
			Self::Array(a) => a.is_empty(),
			Self::Object(o) => o.is_empty(),
			_ => false,
		}
	}
Examples found in repository?
src/object.rs (line 590)
589
590
591
	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
More examples
Hide additional examples
src/print.rs (line 612)
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
	fn fmt_with_size(
		&self,
		f: &mut fmt::Formatter,
		options: &Options,
		indent: usize,
		sizes: &[Size],
		index: &mut usize,
	) -> fmt::Result {
		print_object(
			self.iter().map(|e| (e.key.as_str(), &e.value)),
			f,
			options,
			indent,
			sizes,
			index,
		)
	}
}

pub trait PrecomputeSize {
	fn pre_compute_size(&self, options: &Options, sizes: &mut Vec<Size>) -> Size;
}

impl PrecomputeSize for bool {
	#[inline(always)]
	fn pre_compute_size(&self, _options: &Options, _sizes: &mut Vec<Size>) -> Size {
		if *self {
			Size::Width(4)
		} else {
			Size::Width(5)
		}
	}
}

impl<M> PrecomputeSize for crate::Value<M> {
	fn pre_compute_size(&self, options: &Options, sizes: &mut Vec<Size>) -> Size {
		match self {
			crate::Value::Null => Size::Width(4),
			crate::Value::Boolean(b) => b.pre_compute_size(options, sizes),
			crate::Value::Number(n) => Size::Width(n.as_str().len()),
			crate::Value::String(s) => Size::Width(printed_string_size(s)),
			crate::Value::Array(a) => pre_compute_array_size(a, options, sizes),
			crate::Value::Object(o) => pre_compute_object_size(
				o.iter().map(|e| (e.key.as_str(), &e.value)),
				options,
				sizes,
			),
		}
	}
src/lib.rs (line 692)
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
	pub fn sub_fragments(&self) -> SubFragments<'a, M> {
		match self {
			Self::Value(Value::Array(a)) => SubFragments::Array(a.iter()),
			Self::Value(Value::Object(o)) => SubFragments::Object(o.iter()),
			Self::Entry(e) => SubFragments::Entry(Some(&e.key), Some(&e.value)),
			_ => SubFragments::None,
		}
	}
}

pub enum FragmentRef<'a, M> {
	Value(&'a Meta<Value<M>, M>),
	Entry(&'a object::Entry<M>),
	Key(&'a Meta<object::Key, M>),
}

impl<'a, M> FragmentRef<'a, M> {
	pub fn is_entry(&self) -> bool {
		matches!(self, Self::Entry(_))
	}

	pub fn is_key(&self) -> bool {
		matches!(self, Self::Key(_))
	}

	pub fn is_value(&self) -> bool {
		matches!(self, Self::Value(_))
	}

	pub fn is_null(&self) -> bool {
		matches!(self, Self::Value(Meta(Value::Null, _)))
	}

	pub fn is_number(&self) -> bool {
		matches!(self, Self::Value(Meta(Value::Number(_), _)))
	}

	pub fn is_string(&self) -> bool {
		matches!(self, Self::Value(Meta(Value::String(_), _)))
	}

	pub fn is_array(&self) -> bool {
		matches!(self, Self::Value(Meta(Value::Array(_), _)))
	}

	pub fn is_object(&self) -> bool {
		matches!(self, Self::Value(Meta(Value::Object(_), _)))
	}

	pub fn strip(self) -> StrippedFragmentRef<'a, M> {
		match self {
			Self::Value(v) => StrippedFragmentRef::Value(v.value()),
			Self::Entry(e) => StrippedFragmentRef::Entry(e),
			Self::Key(k) => StrippedFragmentRef::Key(k.value()),
		}
	}
}

impl<'a, M> locspan::Strip for FragmentRef<'a, M> {
	type Stripped = StrippedFragmentRef<'a, M>;

	fn strip(self) -> Self::Stripped {
		self.strip()
	}
}

impl<'a, M> Clone for FragmentRef<'a, M> {
	fn clone(&self) -> Self {
		match self {
			Self::Value(v) => Self::Value(*v),
			Self::Entry(e) => Self::Entry(e),
			Self::Key(k) => Self::Key(*k),
		}
	}
}

impl<'a, M> Copy for FragmentRef<'a, M> {}

impl<'a, M> FragmentRef<'a, M> {
	pub fn sub_fragments(&self) -> SubFragments<'a, M> {
		match self {
			Self::Value(Meta(Value::Array(a), _)) => SubFragments::Array(a.iter()),
			Self::Value(Meta(Value::Object(o), _)) => SubFragments::Object(o.iter()),
			Self::Entry(e) => SubFragments::Entry(Some(&e.key), Some(&e.value)),
			_ => SubFragments::None,
		}
	}
Examples found in repository?
src/object.rs (line 599)
598
599
600
	fn into_iter(self) -> Self::IntoIter {
		self.iter_mut()
	}

Returns an iterator over the values matching the given key.

Runs in O(1) (average).

Returns an iterator over the values matching the given key.

Runs in O(1) (average).

Returns the unique entry value matching the given key.

Returns an error if multiple entries match the key.

Runs in O(1) (average).

Returns the unique entry value matching the given key.

Returns an error if multiple entries match the key.

Runs in O(1) (average).

Returns an iterator over the entries matching the given key.

Runs in O(1) (average).

Examples found in repository?
src/object.rs (line 226)
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
	pub fn get_unique<Q: ?Sized>(
		&self,
		key: &Q,
	) -> Result<Option<&MetaValue<M>>, Duplicate<&Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.get_entries(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(&entry.value)),
			},
			None => Ok(None),
		}
	}

	/// Returns the unique entry value matching the given key.
	///
	/// Returns an error if multiple entries match the key.
	///
	/// Runs in `O(1)` (average).
	pub fn get_unique_mut<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<&mut MetaValue<M>>, Duplicate<&Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let index = {
			let mut entries = self.get_entries_with_index(key);
			match entries.next() {
				Some((i, _)) => match entries.next() {
					Some((j, _)) => Err(Duplicate(i, j)),
					None => Ok(Some(i)),
				},
				None => Ok(None),
			}
		};

		match index {
			Ok(Some(i)) => Ok(Some(&mut self.entries[i].value)),
			Ok(None) => Ok(None),
			Err(Duplicate(i, j)) => Err(Duplicate(&self.entries[i], &self.entries[j])),
		}
	}

	/// Returns an iterator over the entries matching the given key.
	///
	/// Runs in `O(1)` (average).
	pub fn get_entries<Q: ?Sized>(&self, key: &Q) -> Entries<M>
	where
		Q: Hash + Equivalent<Key>,
	{
		let indexes = self
			.indexes
			.get(&self.entries, key)
			.map(IntoIterator::into_iter)
			.unwrap_or_default();
		Entries {
			indexes,
			object: self,
		}
	}

	/// Returns the unique entry matching the given key.
	///
	/// Returns an error if multiple entries match the key.
	///
	/// Runs in `O(1)` (average).
	pub fn get_unique_entry<Q: ?Sized>(
		&self,
		key: &Q,
	) -> Result<Option<&Entry<M>>, Duplicate<&Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.get_entries(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(entry)),
			},
			None => Ok(None),
		}
	}
source

pub fn get_unique_entry<Q>(
    &self,
    key: &Q
) -> Result<Option<&Entry<M>>, Duplicate<&Entry<M>>>where
    Q: Hash + Equivalent<Key> + ?Sized,

Returns the unique entry matching the given key.

Returns an error if multiple entries match the key.

Runs in O(1) (average).

Returns an iterator over the entries matching the given key.

Runs in O(1) (average).

Returns an iterator over the entries matching the given key.

Runs in O(1) (average).

Examples found in repository?
src/object.rs (line 250)
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
	pub fn get_unique_mut<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<&mut MetaValue<M>>, Duplicate<&Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let index = {
			let mut entries = self.get_entries_with_index(key);
			match entries.next() {
				Some((i, _)) => match entries.next() {
					Some((j, _)) => Err(Duplicate(i, j)),
					None => Ok(Some(i)),
				},
				None => Ok(None),
			}
		};

		match index {
			Ok(Some(i)) => Ok(Some(&mut self.entries[i].value)),
			Ok(None) => Ok(None),
			Err(Duplicate(i, j)) => Err(Duplicate(&self.entries[i], &self.entries[j])),
		}
	}
Examples found in repository?
src/object.rs (line 419)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
	pub fn insert(
		&mut self,
		key: Meta<Key, M>,
		value: MetaValue<M>,
	) -> Option<RemovedByInsertion<M>> {
		match self.index_of(key.value()) {
			Some(index) => {
				let mut entry = Entry::new(key, value);
				core::mem::swap(&mut entry, &mut self.entries[index]);
				Some(RemovedByInsertion {
					index,
					first: Some(entry),
					object: self,
				})
			}
			None => {
				self.push(key, value);
				None
			}
		}
	}

	/// Remove all entries associated to the given key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove<'q, Q: ?Sized>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, M, Q>
	where
		Q: Hash + Equivalent<Key>,
	{
		RemovedEntries { key, object: self }
	}

	/// Remove the unique entry associated to the given key.
	///
	/// Returns an error if multiple entries match the key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove_unique<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.remove(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(entry)),
			},
			None => Ok(None),
		}
	}

	/// Recursively maps the metadata inside the object.
	pub fn map_metadata<N>(self, mut f: impl FnMut(M) -> N) -> Object<N> {
		let entries = self
			.entries
			.into_iter()
			.map(|entry| entry.map_metadata(&mut f))
			.collect();

		Object {
			entries,
			indexes: self.indexes,
		}
	}

	/// Tries to recursively maps the metadata inside the object.
	pub fn try_map_metadata<N, E>(
		self,
		mut f: impl FnMut(M) -> Result<N, E>,
	) -> Result<Object<N>, E> {
		let mut entries = Vec::with_capacity(self.len());
		for entry in self.entries {
			entries.push(entry.try_map_metadata(&mut f)?)
		}

		Ok(Object {
			entries,
			indexes: self.indexes,
		})
	}

	/// Sort the entries by key name.
	///
	/// Entries with the same key are sorted by value.
	pub fn sort(&mut self) {
		use locspan::BorrowStripped;
		self.entries.sort_by(|a, b| a.stripped().cmp(b.stripped()));
		self.indexes.clear();

		for i in 0..self.entries.len() {
			self.indexes.insert(&self.entries, i);
		}
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	///
	/// This will canonicalize the entries and sort them by key.
	/// Entries with the same key are sorted by value.
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize_with(&mut self, buffer: &mut ryu_js::Buffer) {
		for (_, item) in self.iter_mut() {
			item.canonicalize_with(buffer);
		}

		self.sort()
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize(&mut self) {
		let mut buffer = ryu_js::Buffer::new();
		self.canonicalize_with(&mut buffer)
	}
}

pub struct IterMut<'a, M>(std::slice::IterMut<'a, Entry<M>>);

impl<'a, M> Iterator for IterMut<'a, M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);

	fn next(&mut self) -> Option<Self::Item> {
		self.0.next().map(|entry| (&entry.key, &mut entry.value))
	}
}

impl<M: PartialEq> PartialEq for Object<M> {
	fn eq(&self, other: &Self) -> bool {
		self.entries == other.entries
	}
}

impl<M: Eq> Eq for Object<M> {}

impl<M: PartialOrd> PartialOrd for Object<M> {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		self.entries.partial_cmp(&other.entries)
	}
}

impl<M: Ord> Ord for Object<M> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.entries.cmp(&other.entries)
	}
}

impl<M: Hash> Hash for Object<M> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.entries.hash(state)
	}
}

impl<M: fmt::Debug> fmt::Debug for Object<M> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_map()
			.entries(self.entries.iter().map(Entry::as_pair))
			.finish()
	}
}

impl<M> From<Vec<Entry<M>>> for Object<M> {
	fn from(entries: Vec<Entry<M>>) -> Self {
		Self::from_vec(entries)
	}
}

impl<'a, M> IntoIterator for &'a Object<M> {
	type Item = &'a Entry<M>;
	type IntoIter = core::slice::Iter<'a, Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
}

impl<'a, M> IntoIterator for &'a mut Object<M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);
	type IntoIter = IterMut<'a, M>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter_mut()
	}
}

impl<M> IntoIterator for Object<M> {
	type Item = Entry<M>;
	type IntoIter = std::vec::IntoIter<Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.entries.into_iter()
	}
}

impl<M> Extend<Entry<M>> for Object<M> {
	fn extend<I: IntoIterator<Item = Entry<M>>>(&mut self, iter: I) {
		for entry in iter {
			self.push_entry(entry);
		}
	}
}

impl<M> FromIterator<Entry<M>> for Object<M> {
	fn from_iter<I: IntoIterator<Item = Entry<M>>>(iter: I) -> Self {
		let mut object = Object::default();
		object.extend(iter);
		object
	}
}

impl<M> Extend<(Meta<Key, M>, MetaValue<M>)> for Object<M> {
	fn extend<I: IntoIterator<Item = (Meta<Key, M>, MetaValue<M>)>>(&mut self, iter: I) {
		for (key, value) in iter {
			self.push(key, value);
		}
	}
}

impl<M> FromIterator<(Meta<Key, M>, MetaValue<M>)> for Object<M> {
	fn from_iter<I: IntoIterator<Item = (Meta<Key, M>, MetaValue<M>)>>(iter: I) -> Self {
		let mut object = Object::default();
		object.extend(iter);
		object
	}
}

pub enum Indexes<'a> {
	Some {
		first: Option<usize>,
		other: core::slice::Iter<'a, usize>,
	},
	None,
}

impl<'a> Default for Indexes<'a> {
	fn default() -> Self {
		Self::None
	}
}

impl<'a> Iterator for Indexes<'a> {
	type Item = usize;

	fn next(&mut self) -> Option<Self::Item> {
		match self {
			Self::Some { first, other } => match first.take() {
				Some(index) => Some(index),
				None => other.next().cloned(),
			},
			Self::None => None,
		}
	}
}

macro_rules! entries_iter {
	($($id:ident <$lft:lifetime> {
		type Item = $item:ty ;

		fn next(&mut $self:ident, $index:ident) { $e:expr }
	})*) => {
		$(
			pub struct $id<$lft, M> {
				indexes: Indexes<$lft>,
				object: &$lft Object<M>
			}

			impl<$lft, M> Iterator for $id<$lft, M> {
				type Item = $item;

				fn next(&mut $self) -> Option<Self::Item> {
					$self.indexes.next().map(|$index| $e)
				}
			}
		)*
	};
}

entries_iter! {
	Values<'a> {
		type Item = &'a MetaValue<M>;

		fn next(&mut self, index) { &self.object.entries[index].value }
	}

	ValuesWithIndex<'a> {
		type Item = (usize, &'a MetaValue<M>);

		fn next(&mut self, index) { (index, &self.object.entries[index].value) }
	}

	Entries<'a> {
		type Item = &'a Entry<M>;

		fn next(&mut self, index) { &self.object.entries[index] }
	}

	EntriesWithIndex<'a> {
		type Item = (usize, &'a Entry<M>);

		fn next(&mut self, index) { (index, &self.object.entries[index]) }
	}
}

macro_rules! entries_iter_mut {
	($($id:ident <$lft:lifetime> {
		type Item = $item:ty ;

		fn next(&mut $self:ident, $index:ident) { $e:expr }
	})*) => {
		$(
			pub struct $id<$lft, M> {
				indexes: Indexes<$lft>,
				entries: &$lft mut [Entry<M>]
			}

			impl<$lft, M> Iterator for $id<$lft, M> {
				type Item = $item;

				fn next(&mut $self) -> Option<Self::Item> {
					$self.indexes.next().map(|$index| $e)
				}
			}
		)*
	};
}

entries_iter_mut! {
	ValuesMut<'a> {
		type Item = &'a mut MetaValue<M>;

		fn next(&mut self, index) {
			// This is safe because there is no aliasing between the values.
			unsafe { core::mem::transmute(&mut self.entries[index].value) }
		}
	}

	ValuesMutWithIndex<'a> {
		type Item = (usize, &'a mut MetaValue<M>);

		fn next(&mut self, index) {
			// This is safe because there is no aliasing between the values.
			unsafe { (index, core::mem::transmute(&mut self.entries[index].value)) }
		}
	}
}

pub struct RemovedByInsertion<'a, M> {
	index: usize,
	first: Option<Entry<M>>,
	object: &'a mut Object<M>,
}

impl<'a, M> Iterator for RemovedByInsertion<'a, M> {
	type Item = Entry<M>;

	fn next(&mut self) -> Option<Self::Item> {
		match self.first.take() {
			Some(entry) => Some(entry),
			None => {
				let key = self.object.entries[self.index].key.value();
				self.object
					.redundant_index_of(key)
					.and_then(|index| self.object.remove_at(index))
			}
		}
	}
}

impl<'a, M> Drop for RemovedByInsertion<'a, M> {
	fn drop(&mut self) {
		self.last();
	}
}

pub struct RemovedEntries<'a, 'q, M, Q: ?Sized>
where
	Q: Hash + Equivalent<Key>,
{
	key: &'q Q,
	object: &'a mut Object<M>,
}

impl<'a, 'q, M, Q: ?Sized> Iterator for RemovedEntries<'a, 'q, M, Q>
where
	Q: Hash + Equivalent<Key>,
{
	type Item = Entry<M>;

	fn next(&mut self) -> Option<Self::Item> {
		self.object
			.index_of(self.key)
			.and_then(|index| self.object.remove_at(index))
	}
Examples found in repository?
src/object.rs (line 779)
773
774
775
776
777
778
779
780
781
782
783
	fn next(&mut self) -> Option<Self::Item> {
		match self.first.take() {
			Some(entry) => Some(entry),
			None => {
				let key = self.object.entries[self.index].key.value();
				self.object
					.redundant_index_of(key)
					.and_then(|index| self.object.remove_at(index))
			}
		}
	}

Push the given key-value pair to the end of the object.

Returns true if the key was not already present in the object, and false otherwise. Any previous entry matching the key is not overridden: duplicates are preserved, in order.

Runs in O(1).

Examples found in repository?
src/object.rs (line 430)
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
	pub fn insert(
		&mut self,
		key: Meta<Key, M>,
		value: MetaValue<M>,
	) -> Option<RemovedByInsertion<M>> {
		match self.index_of(key.value()) {
			Some(index) => {
				let mut entry = Entry::new(key, value);
				core::mem::swap(&mut entry, &mut self.entries[index]);
				Some(RemovedByInsertion {
					index,
					first: Some(entry),
					object: self,
				})
			}
			None => {
				self.push(key, value);
				None
			}
		}
	}

	/// Remove all entries associated to the given key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove<'q, Q: ?Sized>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, M, Q>
	where
		Q: Hash + Equivalent<Key>,
	{
		RemovedEntries { key, object: self }
	}

	/// Remove the unique entry associated to the given key.
	///
	/// Returns an error if multiple entries match the key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove_unique<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.remove(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(entry)),
			},
			None => Ok(None),
		}
	}

	/// Recursively maps the metadata inside the object.
	pub fn map_metadata<N>(self, mut f: impl FnMut(M) -> N) -> Object<N> {
		let entries = self
			.entries
			.into_iter()
			.map(|entry| entry.map_metadata(&mut f))
			.collect();

		Object {
			entries,
			indexes: self.indexes,
		}
	}

	/// Tries to recursively maps the metadata inside the object.
	pub fn try_map_metadata<N, E>(
		self,
		mut f: impl FnMut(M) -> Result<N, E>,
	) -> Result<Object<N>, E> {
		let mut entries = Vec::with_capacity(self.len());
		for entry in self.entries {
			entries.push(entry.try_map_metadata(&mut f)?)
		}

		Ok(Object {
			entries,
			indexes: self.indexes,
		})
	}

	/// Sort the entries by key name.
	///
	/// Entries with the same key are sorted by value.
	pub fn sort(&mut self) {
		use locspan::BorrowStripped;
		self.entries.sort_by(|a, b| a.stripped().cmp(b.stripped()));
		self.indexes.clear();

		for i in 0..self.entries.len() {
			self.indexes.insert(&self.entries, i);
		}
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	///
	/// This will canonicalize the entries and sort them by key.
	/// Entries with the same key are sorted by value.
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize_with(&mut self, buffer: &mut ryu_js::Buffer) {
		for (_, item) in self.iter_mut() {
			item.canonicalize_with(buffer);
		}

		self.sort()
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize(&mut self) {
		let mut buffer = ryu_js::Buffer::new();
		self.canonicalize_with(&mut buffer)
	}
}

pub struct IterMut<'a, M>(std::slice::IterMut<'a, Entry<M>>);

impl<'a, M> Iterator for IterMut<'a, M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);

	fn next(&mut self) -> Option<Self::Item> {
		self.0.next().map(|entry| (&entry.key, &mut entry.value))
	}
}

impl<M: PartialEq> PartialEq for Object<M> {
	fn eq(&self, other: &Self) -> bool {
		self.entries == other.entries
	}
}

impl<M: Eq> Eq for Object<M> {}

impl<M: PartialOrd> PartialOrd for Object<M> {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		self.entries.partial_cmp(&other.entries)
	}
}

impl<M: Ord> Ord for Object<M> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.entries.cmp(&other.entries)
	}
}

impl<M: Hash> Hash for Object<M> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.entries.hash(state)
	}
}

impl<M: fmt::Debug> fmt::Debug for Object<M> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_map()
			.entries(self.entries.iter().map(Entry::as_pair))
			.finish()
	}
}

impl<M> From<Vec<Entry<M>>> for Object<M> {
	fn from(entries: Vec<Entry<M>>) -> Self {
		Self::from_vec(entries)
	}
}

impl<'a, M> IntoIterator for &'a Object<M> {
	type Item = &'a Entry<M>;
	type IntoIter = core::slice::Iter<'a, Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
}

impl<'a, M> IntoIterator for &'a mut Object<M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);
	type IntoIter = IterMut<'a, M>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter_mut()
	}
}

impl<M> IntoIterator for Object<M> {
	type Item = Entry<M>;
	type IntoIter = std::vec::IntoIter<Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.entries.into_iter()
	}
}

impl<M> Extend<Entry<M>> for Object<M> {
	fn extend<I: IntoIterator<Item = Entry<M>>>(&mut self, iter: I) {
		for entry in iter {
			self.push_entry(entry);
		}
	}
}

impl<M> FromIterator<Entry<M>> for Object<M> {
	fn from_iter<I: IntoIterator<Item = Entry<M>>>(iter: I) -> Self {
		let mut object = Object::default();
		object.extend(iter);
		object
	}
}

impl<M> Extend<(Meta<Key, M>, MetaValue<M>)> for Object<M> {
	fn extend<I: IntoIterator<Item = (Meta<Key, M>, MetaValue<M>)>>(&mut self, iter: I) {
		for (key, value) in iter {
			self.push(key, value);
		}
	}
More examples
Hide additional examples
src/parse/value.rs (line 167)
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
	fn parse_spanned<C, F, E>(
		parser: &mut Parser<C, F, E>,
		context: Context,
	) -> Result<Meta<Self, Span>, Meta<Error<M, E>, M>>
	where
		C: Iterator<Item = Result<DecodedChar, E>>,
		F: FnMut(Span) -> M,
	{
		enum Item<M> {
			Array(Meta<Array<M>, Span>),
			ArrayItem(Meta<Array<M>, Span>),
			Object(Meta<Object<M>, Span>),
			ObjectEntry(Meta<Object<M>, Span>, Meta<Key, M>),
		}

		let mut stack: Vec<Item<M>> = vec![];
		let mut value: Option<Meta<Value<M>, Span>> = None;

		fn stack_context<M>(stack: &[Item<M>], root: Context) -> Context {
			match stack.last() {
				Some(Item::Array(_) | Item::ArrayItem(_)) => Context::Array,
				Some(Item::Object(_)) => Context::ObjectKey,
				Some(Item::ObjectEntry(_, _)) => Context::ObjectValue,
				None => root,
			}
		}

		loop {
			match stack.pop() {
				None => match Fragment::value_or_parse(
					value.take(),
					parser,
					stack_context(&stack, context),
				)? {
					Meta(Fragment::Value(value), span) => break Ok(Meta(value, span)),
					Meta(Fragment::BeginArray, span) => {
						stack.push(Item::ArrayItem(Meta(Array::new(), span)))
					}
					Meta(Fragment::BeginObject(key), span) => {
						stack.push(Item::ObjectEntry(Meta(Object::new(), span), key))
					}
				},
				Some(Item::Array(Meta(array, span))) => {
					match array::ContinueFragment::parse_spanned(
						parser,
						stack_context(&stack, context),
					)? {
						Meta(array::ContinueFragment::Item, comma_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(comma_span))))
						}
						Meta(array::ContinueFragment::End, closing_span) => {
							parser.skip_trailing_whitespaces(stack_context(&stack, context))?;
							value = Some(Meta(Value::Array(array), span.union(closing_span)))
						}
					}
				}
				Some(Item::ArrayItem(Meta(mut array, span))) => {
					match Fragment::value_or_parse(value.take(), parser, Context::Array)? {
						Meta(Fragment::Value(value), value_span) => {
							array.push(Meta(value, parser.position.metadata_at(value_span)));
							stack.push(Item::Array(Meta(array, span.union(value_span))));
						}
						Meta(Fragment::BeginArray, value_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(value_span))));
							stack.push(Item::ArrayItem(Meta(Array::new(), value_span)))
						}
						Meta(Fragment::BeginObject(value_key), value_span) => {
							stack.push(Item::ArrayItem(Meta(array, span.union(value_span))));
							stack.push(Item::ObjectEntry(
								Meta(Object::new(), value_span),
								value_key,
							))
						}
					}
				}
				Some(Item::Object(Meta(object, span))) => {
					match object::ContinueFragment::parse_spanned(
						parser,
						stack_context(&stack, context),
					)? {
						Meta(object::ContinueFragment::Entry(key), comma_key_span) => stack.push(
							Item::ObjectEntry(Meta(object, span.union(comma_key_span)), key),
						),
						Meta(object::ContinueFragment::End, closing_span) => {
							parser.skip_trailing_whitespaces(stack_context(&stack, context))?;
							value = Some(Meta(Value::Object(object), span.union(closing_span)))
						}
					}
				}
				Some(Item::ObjectEntry(Meta(mut object, span), key)) => {
					match Fragment::value_or_parse(value.take(), parser, Context::ObjectValue)? {
						Meta(Fragment::Value(value), value_span) => {
							object.push(key, Meta(value, parser.position.metadata_at(value_span)));
							stack.push(Item::Object(Meta(object, span.union(value_span))));
						}
						Meta(Fragment::BeginArray, value_span) => {
							stack
								.push(Item::ObjectEntry(Meta(object, span.union(value_span)), key));
							stack.push(Item::ArrayItem(Meta(Array::new(), value_span)))
						}
						Meta(Fragment::BeginObject(value_key), value_span) => {
							stack
								.push(Item::ObjectEntry(Meta(object, span.union(value_span)), key));
							stack.push(Item::ObjectEntry(
								Meta(Object::new(), value_span),
								value_key,
							))
						}
					}
				}
			}
		}
	}
source

pub fn push_entry(&mut self, entry: Entry<M>) -> bool

Examples found in repository?
src/object.rs (line 389)
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
	pub fn push(&mut self, key: Meta<Key, M>, value: MetaValue<M>) -> bool {
		self.push_entry(Entry::new(key, value))
	}

	pub fn push_entry(&mut self, entry: Entry<M>) -> bool {
		let index = self.entries.len();
		self.entries.push(entry);
		self.indexes.insert(&self.entries, index)
	}

	/// Removes the entry at the given index.
	pub fn remove_at(&mut self, index: usize) -> Option<Entry<M>> {
		if index < self.entries.len() {
			self.indexes.remove(&self.entries, index);
			self.indexes.shift(index);
			Some(self.entries.remove(index))
		} else {
			None
		}
	}

	/// Inserts the given key-value pair.
	///
	/// If one or more entries are already matching the given key,
	/// all of them are removed and returned in the resulting iterator.
	/// Otherwise, `None` is returned.
	pub fn insert(
		&mut self,
		key: Meta<Key, M>,
		value: MetaValue<M>,
	) -> Option<RemovedByInsertion<M>> {
		match self.index_of(key.value()) {
			Some(index) => {
				let mut entry = Entry::new(key, value);
				core::mem::swap(&mut entry, &mut self.entries[index]);
				Some(RemovedByInsertion {
					index,
					first: Some(entry),
					object: self,
				})
			}
			None => {
				self.push(key, value);
				None
			}
		}
	}

	/// Remove all entries associated to the given key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove<'q, Q: ?Sized>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, M, Q>
	where
		Q: Hash + Equivalent<Key>,
	{
		RemovedEntries { key, object: self }
	}

	/// Remove the unique entry associated to the given key.
	///
	/// Returns an error if multiple entries match the key.
	///
	/// Runs in `O(n)` time (average).
	pub fn remove_unique<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.remove(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(entry)),
			},
			None => Ok(None),
		}
	}

	/// Recursively maps the metadata inside the object.
	pub fn map_metadata<N>(self, mut f: impl FnMut(M) -> N) -> Object<N> {
		let entries = self
			.entries
			.into_iter()
			.map(|entry| entry.map_metadata(&mut f))
			.collect();

		Object {
			entries,
			indexes: self.indexes,
		}
	}

	/// Tries to recursively maps the metadata inside the object.
	pub fn try_map_metadata<N, E>(
		self,
		mut f: impl FnMut(M) -> Result<N, E>,
	) -> Result<Object<N>, E> {
		let mut entries = Vec::with_capacity(self.len());
		for entry in self.entries {
			entries.push(entry.try_map_metadata(&mut f)?)
		}

		Ok(Object {
			entries,
			indexes: self.indexes,
		})
	}

	/// Sort the entries by key name.
	///
	/// Entries with the same key are sorted by value.
	pub fn sort(&mut self) {
		use locspan::BorrowStripped;
		self.entries.sort_by(|a, b| a.stripped().cmp(b.stripped()));
		self.indexes.clear();

		for i in 0..self.entries.len() {
			self.indexes.insert(&self.entries, i);
		}
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	///
	/// This will canonicalize the entries and sort them by key.
	/// Entries with the same key are sorted by value.
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize_with(&mut self, buffer: &mut ryu_js::Buffer) {
		for (_, item) in self.iter_mut() {
			item.canonicalize_with(buffer);
		}

		self.sort()
	}

	/// Puts this JSON object in canonical form according to
	/// [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785#name-generation-of-canonical-jso).
	#[cfg(feature = "canonicalize")]
	pub fn canonicalize(&mut self) {
		let mut buffer = ryu_js::Buffer::new();
		self.canonicalize_with(&mut buffer)
	}
}

pub struct IterMut<'a, M>(std::slice::IterMut<'a, Entry<M>>);

impl<'a, M> Iterator for IterMut<'a, M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);

	fn next(&mut self) -> Option<Self::Item> {
		self.0.next().map(|entry| (&entry.key, &mut entry.value))
	}
}

impl<M: PartialEq> PartialEq for Object<M> {
	fn eq(&self, other: &Self) -> bool {
		self.entries == other.entries
	}
}

impl<M: Eq> Eq for Object<M> {}

impl<M: PartialOrd> PartialOrd for Object<M> {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		self.entries.partial_cmp(&other.entries)
	}
}

impl<M: Ord> Ord for Object<M> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.entries.cmp(&other.entries)
	}
}

impl<M: Hash> Hash for Object<M> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.entries.hash(state)
	}
}

impl<M: fmt::Debug> fmt::Debug for Object<M> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_map()
			.entries(self.entries.iter().map(Entry::as_pair))
			.finish()
	}
}

impl<M> From<Vec<Entry<M>>> for Object<M> {
	fn from(entries: Vec<Entry<M>>) -> Self {
		Self::from_vec(entries)
	}
}

impl<'a, M> IntoIterator for &'a Object<M> {
	type Item = &'a Entry<M>;
	type IntoIter = core::slice::Iter<'a, Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
}

impl<'a, M> IntoIterator for &'a mut Object<M> {
	type Item = (&'a Meta<Key, M>, &'a mut MetaValue<M>);
	type IntoIter = IterMut<'a, M>;

	fn into_iter(self) -> Self::IntoIter {
		self.iter_mut()
	}
}

impl<M> IntoIterator for Object<M> {
	type Item = Entry<M>;
	type IntoIter = std::vec::IntoIter<Entry<M>>;

	fn into_iter(self) -> Self::IntoIter {
		self.entries.into_iter()
	}
}

impl<M> Extend<Entry<M>> for Object<M> {
	fn extend<I: IntoIterator<Item = Entry<M>>>(&mut self, iter: I) {
		for entry in iter {
			self.push_entry(entry);
		}
	}

Removes the entry at the given index.

Examples found in repository?
src/object.rs (line 780)
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
	fn next(&mut self) -> Option<Self::Item> {
		match self.first.take() {
			Some(entry) => Some(entry),
			None => {
				let key = self.object.entries[self.index].key.value();
				self.object
					.redundant_index_of(key)
					.and_then(|index| self.object.remove_at(index))
			}
		}
	}
}

impl<'a, M> Drop for RemovedByInsertion<'a, M> {
	fn drop(&mut self) {
		self.last();
	}
}

pub struct RemovedEntries<'a, 'q, M, Q: ?Sized>
where
	Q: Hash + Equivalent<Key>,
{
	key: &'q Q,
	object: &'a mut Object<M>,
}

impl<'a, 'q, M, Q: ?Sized> Iterator for RemovedEntries<'a, 'q, M, Q>
where
	Q: Hash + Equivalent<Key>,
{
	type Item = Entry<M>;

	fn next(&mut self) -> Option<Self::Item> {
		self.object
			.index_of(self.key)
			.and_then(|index| self.object.remove_at(index))
	}

Inserts the given key-value pair.

If one or more entries are already matching the given key, all of them are removed and returned in the resulting iterator. Otherwise, None is returned.

Remove all entries associated to the given key.

Runs in O(n) time (average).

Examples found in repository?
src/object.rs (line 458)
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
	pub fn remove_unique<Q: ?Sized>(
		&mut self,
		key: &Q,
	) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>
	where
		Q: Hash + Equivalent<Key>,
	{
		let mut entries = self.remove(key);

		match entries.next() {
			Some(entry) => match entries.next() {
				Some(duplicate) => Err(Duplicate(entry, duplicate)),
				None => Ok(Some(entry)),
			},
			None => Ok(None),
		}
	}

Remove the unique entry associated to the given key.

Returns an error if multiple entries match the key.

Runs in O(n) time (average).

Recursively maps the metadata inside the object.

Examples found in repository?
src/lib.rs (line 449)
438
439
440
441
442
443
444
445
446
447
448
449
450
451
	pub fn map_metadata<N>(self, mut f: impl FnMut(M) -> N) -> Value<N> {
		match self {
			Self::Null => Value::Null,
			Self::Boolean(b) => Value::Boolean(b),
			Self::Number(n) => Value::Number(n),
			Self::String(s) => Value::String(s),
			Self::Array(a) => Value::Array(
				a.into_iter()
					.map(|Meta(item, meta)| Meta(item.map_metadata(&mut f), f(meta)))
					.collect(),
			),
			Self::Object(o) => Value::Object(o.map_metadata(f)),
		}
	}

Tries to recursively maps the metadata inside the object.

Examples found in repository?
src/lib.rs (line 470)
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
	pub fn try_map_metadata<N, E>(
		self,
		mut f: impl FnMut(M) -> Result<N, E>,
	) -> Result<Value<N>, E> {
		match self {
			Self::Null => Ok(Value::Null),
			Self::Boolean(b) => Ok(Value::Boolean(b)),
			Self::Number(n) => Ok(Value::Number(n)),
			Self::String(s) => Ok(Value::String(s)),
			Self::Array(a) => {
				let mut items = Vec::with_capacity(a.len());
				for item in a {
					items.push(item.try_map_metadata_recursively(&mut f)?)
				}
				Ok(Value::Array(items))
			}
			Self::Object(o) => Ok(Value::Object(o.try_map_metadata(f)?)),
		}
	}

Sort the entries by key name.

Entries with the same key are sorted by value.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Wraps self inside a Meta<Self, M> using the given metadata. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.