Skip to content
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
51 changes: 50 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#![warn(missing_docs)]

/*!
# An owning reference.

Expand Down Expand Up @@ -242,6 +241,7 @@ fn main() {
}
```
*/
use std::marker::PhantomData;

extern crate stable_deref_trait;
pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
Expand All @@ -260,6 +260,12 @@ pub struct OwningRef<O, T: ?Sized> {
reference: *const T,
}

pub struct OwningIter<'a, O, I: Iterator<Item=&'a E>, E: 'a> {
owner: O,
iter: I,
phantom: PhantomData<&'a E>,
}

/// An mutable owning reference.
///
/// This wraps an owner `O` and a reference `&mut T` pointing
Expand Down Expand Up @@ -989,6 +995,33 @@ impl<O, T: ?Sized> Clone for OwningRef<O, T>
}
}

impl<'a, O, T: Iterator<Item=&'a E>, E: 'a> Iterator for OwningIter<'a, O, T, E>
where O: CloneStableAddress,
{
type Item = OwningRef<O, E>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|v| OwningRef {
owner: self.owner.clone(),
reference: v,
})
}
}

impl<'a, O, T: 'a> OwningRef<O, T>
where O: CloneStableAddress,
{
pub fn owning_iter<E: 'a>(self)
-> OwningIter<'a, O, <&'a T as IntoIterator>::IntoIter, E>
where &'a T: IntoIterator<Item=&'a E>,
{
OwningIter {
owner: self.owner.clone(),
iter: unsafe { (&*self.reference).into_iter() },
phantom: PhantomData,
}
}
}

unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
where O: CloneStableAddress {}

Expand Down Expand Up @@ -1257,6 +1290,22 @@ mod tests {
assert!(os.iter().all(|e| &e[..] == "hello world"));
}

#[test]
fn erased_iter() {
let items: Vec<String> = vec!["hello".into(), "world".into()];
let rc = RcRef::new(Rc::new(items));
let iterator: Box<Iterator<Item=RcRef<Erased, str>>>;
iterator = Box::new(rc.owning_iter().map(|rc|
rc.map(|x| AsRef::<str>::as_ref(x)).erase_owner()
));
assert_eq!(
"[OwningRef { owner: <Erased>, \
reference: \"hello\" }, \
OwningRef { owner: <Erased>, reference: \"world\" }]",
format!("{:?}", iterator.collect::<Vec<_>>()));
}


#[test]
fn non_static_erased_owner() {
let foo = [413, 612];
Expand Down