pub trait RIterator {
type Item;
// Required methods
fn next(&self) -> Option<Self::Item>;
fn size_hint(&self) -> (i64, Option<i64>);
// Provided methods
fn count(&self) -> i64 { ... }
fn collect_n(&self, n: i32) -> Vec<Self::Item> { ... }
fn skip(&self, n: i32) -> i32 { ... }
fn nth(&self, n: i32) -> Option<Self::Item> { ... }
}Expand description
Adapter trait for std::iter::Iterator.
Provides iterator operations for R, allowing Rust iterators to be consumed
element-by-element from R code. Since iterators are stateful, the wrapper
type should use interior mutability (e.g., RefCell).
§Methods
next()- Get the next element, or None if exhaustedsize_hint()- Get estimated remaining elements asc(lower, upper)count()- Consume and count remaining elementscollect_n(n)- Collect up to n elements into a vectorskip(n)- Skip n elementsnth(n)- Get the nth element (0-indexed)
§Example
use std::cell::RefCell;
#[derive(ExternalPtr)]
struct MyIter(RefCell<std::vec::IntoIter<i32>>);
impl MyIter {
fn new(data: Vec<i32>) -> Self {
Self(RefCell::new(data.into_iter()))
}
}
impl RIterator for MyIter {
type Item = i32;
fn next(&self) -> Option<Self::Item> {
self.0.borrow_mut().next()
}
fn size_hint(&self) -> (i64, Option<i64>) {
let (lo, hi) = self.0.borrow().size_hint();
(lo as i64, hi.map(|h| h as i64))
}
}
#[miniextendr]
impl RIterator for MyIter {}In R (note: next is a reserved word, so expose as next_item or similar):
it <- MyIter$new(c(1L, 2L, 3L))
it$next_item() # 1L
it$next_item() # 2L
it$size_hint() # c(1, 1) - one element remaining
it$next_item() # 3L
it$next_item() # NULL (exhausted)§Design Note
Unlike other adapter traits, RIterator does NOT have a blanket impl
because iterators require &mut self for next(), but R’s ExternalPtr
pattern typically provides &self. Users must implement this trait
manually using interior mutability (RefCell, Mutex, etc.).
Required Associated Types§
Required Methods§
Sourcefn next(&self) -> Option<Self::Item>
fn next(&self) -> Option<Self::Item>
Get the next element from the iterator.
Returns Some(item) if there are more elements, None if exhausted.
None maps to NULL in R.
Sourcefn size_hint(&self) -> (i64, Option<i64>)
fn size_hint(&self) -> (i64, Option<i64>)
Get the estimated number of remaining elements.
Returns (lower_bound, upper_bound) where upper_bound is None if unknown.
In R, this becomes c(lower, upper) where upper is NA if unknown.
Skipped from trait ABI because tuples don’t have R conversions. Expose via manual forwarding or custom wrapper methods.
Provided Methods§
Sourcefn count(&self) -> i64
fn count(&self) -> i64
Consume the iterator and count remaining elements.
Warning: This exhausts the iterator.
Sourcefn collect_n(&self, n: i32) -> Vec<Self::Item>
fn collect_n(&self, n: i32) -> Vec<Self::Item>
Collect up to n elements into a vector.
Returns fewer than n elements if the iterator is exhausted first.