Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement IntoIterator for Object. #191

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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