Adding in Array::iter and Array::to_vec (#1909)

* Adding in Array::iter and Array::to_vec

* Changing ArrayIter to use std::ops::Range
This commit is contained in:
Pauan
2019-12-17 18:40:33 +01:00
committed by Alex Crichton
parent cbfefb312c
commit 221514acb9
2 changed files with 118 additions and 0 deletions

View File

@ -425,6 +425,61 @@ extern "C" {
pub fn unshift(this: &Array, value: &JsValue) -> u32;
}
/// Iterator returned by `Array::iter`
#[derive(Debug, Clone)]
pub struct ArrayIter<'a> {
range: std::ops::Range<u32>,
array: &'a Array,
}
impl<'a> std::iter::Iterator for ArrayIter<'a> {
type Item = JsValue;
fn next(&mut self) -> Option<Self::Item> {
let index = self.range.next()?;
Some(self.array.get(index))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.range.size_hint()
}
}
impl<'a> std::iter::DoubleEndedIterator for ArrayIter<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
let index = self.range.next_back()?;
Some(self.array.get(index))
}
}
impl<'a> std::iter::FusedIterator for ArrayIter<'a> {}
impl<'a> std::iter::ExactSizeIterator for ArrayIter<'a> {}
impl Array {
/// Returns an iterator over the values of the JS array.
pub fn iter(&self) -> ArrayIter<'_> {
ArrayIter {
range: 0..self.length(),
array: self,
}
}
/// Converts the JS array into a new Vec.
pub fn to_vec(&self) -> Vec<JsValue> {
let len = self.length();
let mut output = Vec::with_capacity(len as usize);
for i in 0..len {
output.push(self.get(i));
}
output
}
}
// TODO pre-initialize the Array with the correct length using TrustedLen
impl<A> std::iter::FromIterator<A> for Array
where