mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-21 08:41:35 +00:00
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:
@ -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
|
||||
|
Reference in New Issue
Block a user