Struct json_syntax::object::Object
source · pub struct Object<M = ()> { /* private fields */ }
Expand description
Object.
Implementations§
source§impl<M> Object<M>
impl<M> Object<M>
sourcepub fn new() -> Self
pub fn new() -> Self
Examples found in repository?
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,
))
}
}
}
}
}
}
pub fn capacity(&self) -> usize
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Examples found in repository?
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,
})
}
pub fn entries(&self) -> &[Entry<M>]
sourcepub fn iter(&self) -> Iter<'_, Entry<M>>
pub fn iter(&self) -> Iter<'_, Entry<M>>
Examples found in repository?
More examples
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,
),
}
}
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,
}
}
sourcepub fn get<Q>(&self, key: &Q) -> Values<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get<Q>(&self, key: &Q) -> Values<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Returns an iterator over the values matching the given key.
Runs in O(1)
(average).
sourcepub fn get_mut<Q>(&mut self, key: &Q) -> ValuesMut<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_mut<Q>(&mut self, key: &Q) -> ValuesMut<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Returns an iterator over the values matching the given key.
Runs in O(1)
(average).
sourcepub fn get_unique<Q>(
&self,
key: &Q
) -> Result<Option<&MetaValue<M>>, Duplicate<&Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_unique<Q>(
&self,
key: &Q
) -> Result<Option<&MetaValue<M>>, Duplicate<&Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
Returns the unique entry value matching the given key.
Returns an error if multiple entries match the key.
Runs in O(1)
(average).
sourcepub fn get_unique_mut<Q>(
&mut self,
key: &Q
) -> Result<Option<&mut MetaValue<M>>, Duplicate<&Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_unique_mut<Q>(
&mut self,
key: &Q
) -> Result<Option<&mut MetaValue<M>>, Duplicate<&Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
Returns the unique entry value matching the given key.
Returns an error if multiple entries match the key.
Runs in O(1)
(average).
sourcepub fn get_entries<Q>(&self, key: &Q) -> Entries<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_entries<Q>(&self, key: &Q) -> Entries<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Returns an iterator over the entries matching the given key.
Runs in O(1)
(average).
Examples found in repository?
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),
}
}
sourcepub fn get_unique_entry<Q>(
&self,
key: &Q
) -> Result<Option<&Entry<M>>, Duplicate<&Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
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).
sourcepub fn get_with_index<Q>(&self, key: &Q) -> ValuesWithIndex<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_with_index<Q>(&self, key: &Q) -> ValuesWithIndex<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Returns an iterator over the entries matching the given key.
Runs in O(1)
(average).
sourcepub fn get_entries_with_index<Q>(&self, key: &Q) -> EntriesWithIndex<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn get_entries_with_index<Q>(&self, key: &Q) -> EntriesWithIndex<'_, M> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Returns an iterator over the entries matching the given key.
Runs in O(1)
(average).
Examples found in repository?
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])),
}
}
sourcepub fn index_of<Q>(&self, key: &Q) -> Option<usize>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn index_of<Q>(&self, key: &Q) -> Option<usize>where
Q: Hash + Equivalent<Key> + ?Sized,
Examples found in repository?
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))
}
sourcepub fn redundant_index_of<Q>(&self, key: &Q) -> Option<usize>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn redundant_index_of<Q>(&self, key: &Q) -> Option<usize>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn indexes_of<Q>(&self, key: &Q) -> Indexes<'_> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn first(&self) -> Option<&Entry<M>>
pub fn last(&self) -> Option<&Entry<M>>
sourcepub fn push(&mut self, key: Meta<Key, M>, value: MetaValue<M>) -> bool
pub fn push(&mut self, key: Meta<Key, M>, value: MetaValue<M>) -> bool
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?
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
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,
))
}
}
}
}
}
}
sourcepub fn push_entry(&mut self, entry: Entry<M>) -> bool
pub fn push_entry(&mut self, entry: Entry<M>) -> bool
Examples found in repository?
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);
}
}
sourcepub fn remove_at(&mut self, index: usize) -> Option<Entry<M>>
pub fn remove_at(&mut self, index: usize) -> Option<Entry<M>>
Removes the entry at the given index.
Examples found in repository?
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))
}
sourcepub fn insert(
&mut self,
key: Meta<Key, M>,
value: MetaValue<M>
) -> Option<RemovedByInsertion<'_, M>>
pub fn insert(
&mut self,
key: Meta<Key, M>,
value: MetaValue<M>
) -> Option<RemovedByInsertion<'_, M>>
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.
sourcepub fn remove<'q, Q>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, M, Q> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
pub fn remove<'q, Q>(&mut self, key: &'q Q) -> RemovedEntries<'_, 'q, M, Q> ⓘwhere
Q: Hash + Equivalent<Key> + ?Sized,
Remove all entries associated to the given key.
Runs in O(n)
time (average).
Examples found in repository?
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),
}
}
sourcepub fn remove_unique<Q>(
&mut self,
key: &Q
) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
pub fn remove_unique<Q>(
&mut self,
key: &Q
) -> Result<Option<Entry<M>>, Duplicate<Entry<M>>>where
Q: Hash + Equivalent<Key> + ?Sized,
Remove the unique entry associated to the given key.
Returns an error if multiple entries match the key.
Runs in O(n)
time (average).
sourcepub fn map_metadata<N>(self, f: impl FnMut(M) -> N) -> Object<N>
pub fn map_metadata<N>(self, f: impl FnMut(M) -> N) -> Object<N>
Recursively maps the metadata inside the object.
Examples found in repository?
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)),
}
}
sourcepub fn try_map_metadata<N, E>(
self,
f: impl FnMut(M) -> Result<N, E>
) -> Result<Object<N>, E>
pub fn try_map_metadata<N, E>(
self,
f: impl FnMut(M) -> Result<N, E>
) -> Result<Object<N>, E>
Tries to recursively maps the metadata inside the object.
Examples found in repository?
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)?)),
}
}
Trait Implementations§
source§impl<M> Extend<(Meta<SmallString<[u8; 16]>, M>, Meta<Value<M>, M>)> for Object<M>
impl<M> Extend<(Meta<SmallString<[u8; 16]>, M>, Meta<Value<M>, M>)> for Object<M>
source§fn extend<I: IntoIterator<Item = (Meta<Key, M>, MetaValue<M>)>>(
&mut self,
iter: I
)
fn extend<I: IntoIterator<Item = (Meta<Key, M>, MetaValue<M>)>>(
&mut self,
iter: I
)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<M> Extend<Entry<M>> for Object<M>
impl<M> Extend<Entry<M>> for Object<M>
source§fn extend<I: IntoIterator<Item = Entry<M>>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = Entry<M>>>(&mut self, iter: I)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<M> FromIterator<(Meta<SmallString<[u8; 16]>, M>, Meta<Value<M>, M>)> for Object<M>
impl<M> FromIterator<(Meta<SmallString<[u8; 16]>, M>, Meta<Value<M>, M>)> for Object<M>
source§impl<M> FromIterator<Entry<M>> for Object<M>
impl<M> FromIterator<Entry<M>> for Object<M>
source§impl<'a, M> IntoIterator for &'a Object<M>
impl<'a, M> IntoIterator for &'a Object<M>
source§impl<'a, M> IntoIterator for &'a mut Object<M>
impl<'a, M> IntoIterator for &'a mut Object<M>
source§impl<M> IntoIterator for Object<M>
impl<M> IntoIterator for Object<M>
source§impl<M: Ord> Ord for Object<M>
impl<M: Ord> Ord for Object<M>
source§impl<M: PartialEq> PartialEq<Object<M>> for Object<M>
impl<M: PartialEq> PartialEq<Object<M>> for Object<M>
source§impl<M: PartialOrd> PartialOrd<Object<M>> for Object<M>
impl<M: PartialOrd> PartialOrd<Object<M>> for Object<M>
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self
and other
) and is used by the <=
operator. Read moresource§impl<M> PrintWithSize for Object<M>
impl<M> PrintWithSize for Object<M>
source§impl<M> StrippedHash for Object<M>
impl<M> StrippedHash for Object<M>
fn stripped_hash<H: Hasher>(&self, state: &mut H)
source§impl<M> StrippedOrd for Object<M>
impl<M> StrippedOrd for Object<M>
fn stripped_cmp(&self, other: &Self) -> Ordering
source§impl<M, __M> StrippedPartialEq<Object<__M>> for Object<M>
impl<M, __M> StrippedPartialEq<Object<__M>> for Object<M>
fn stripped_eq(&self, other: &Object<__M>) -> bool
source§impl<M, __M> StrippedPartialOrd<Object<__M>> for Object<M>
impl<M, __M> StrippedPartialOrd<Object<__M>> for Object<M>
impl<M: Eq> Eq for Object<M>
impl<M> StrippedEq for Object<M>
Auto Trait Implementations§
impl<M> RefUnwindSafe for Object<M>where
M: RefUnwindSafe,
impl<M> Send for Object<M>where
M: Send,
impl<M> Sync for Object<M>where
M: Sync,
impl<M> Unpin for Object<M>where
M: Unpin,
impl<M> UnwindSafe for Object<M>where
M: UnwindSafe,
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.