Skip to content

Commit

Permalink
Merge pull request #1 from rustadopt/pr191
Browse files Browse the repository at this point in the history
(json PR 191) Implement `IntoIterator` for `Object`.

Resolves maciejhirsz/json-rust#190
  • Loading branch information
gierens authored Aug 25, 2023
2 parents 5945bf3 + 3ba358e commit e9a67d7
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion src/object.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{ ptr, mem, str, slice, fmt };
use std::{ ptr, mem, str, slice, vec, fmt };
use std::ops::{ Index, IndexMut, Deref };
use std::iter::FromIterator;

Expand Down Expand Up @@ -176,6 +176,24 @@ impl Clone for Key {
}
}

impl From<Key> for String {
fn from(key: Key) -> String {
unsafe {
if key.len > KEY_BUF_LEN {
// Construct a `String` out of the `key_ptr`. Since the key is
// always allocated from a slice, the capacity is equal to length.
String::from_raw_parts(
key.ptr,
key.len,
key.len
)
} else {
String::from_utf8_unchecked(key.buf[0..key.len].to_vec())
}
}
}
}

#[derive(Clone)]
struct Node {
// String-esque key abstraction
Expand Down Expand Up @@ -643,6 +661,45 @@ impl<'a> ExactSizeIterator for IterMut<'a> {
}
}

pub struct IntoIter {
inner: vec::IntoIter<Node>
}

impl Iterator for IntoIter {
type Item = (String, JsonValue);

#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|node| (node.key.into(), node.value))
}
}

impl DoubleEndedIterator for IntoIter {
#[inline(always)]
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(|node| (node.key.into(), node.value))
}
}

impl ExactSizeIterator for IntoIter {
#[inline(always)]
fn len(&self) -> usize {
self.inner.len()
}
}

impl IntoIterator for Object {
type Item = (String, JsonValue);
type IntoIter = IntoIter;

#[inline(always)]
fn into_iter(self) -> IntoIter {
IntoIter {
inner: self.store.into_iter()
}
}
}

/// Implements indexing by `&str` to easily access object members:
///
/// ## Example
Expand Down

0 comments on commit e9a67d7

Please sign in to comment.