Skip to content

Commit

Permalink
Implement Space::atom_iter for DynSpace
Browse files Browse the repository at this point in the history
  • Loading branch information
vsbogd committed Sep 24, 2024
1 parent 479afb1 commit ab9c0c1
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion lib/src/space/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod module;
use std::fmt::Display;
use std::rc::{Rc, Weak};
use std::cell::{RefCell, Ref, RefMut};
use std::ops::Deref;

use crate::common::FlexRef;
use crate::atom::*;
Expand Down Expand Up @@ -324,7 +325,7 @@ impl Space for DynSpace {
self.0.borrow().atom_count()
}
fn atom_iter(&self) -> Option<Box<dyn Iterator<Item=&Atom> + '_>> {
None
DynSpaceIter::new(self)
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
None
Expand All @@ -334,6 +335,37 @@ impl Space for DynSpace {
}
}

struct DynSpaceIter<'a> {
space_ref: Ref<'a, dyn Space>,
space_iter: Option<Box<dyn Iterator<Item=&'a Atom> + 'a>>,
}

impl<'a> DynSpaceIter<'a> {
fn new(space: &'a DynSpace) -> Option<Box<dyn Iterator<Item=&Atom> + 'a>> {
let space_ref = Ref::map(space.borrow(), SpaceMut::as_space);
let mut iter = Self{
space_ref,
space_iter: None,
};
let space_ptr = iter.space_ref.deref() as *const dyn Space;
match unsafe{ (*space_ptr).atom_iter() } {
Some(it) => {
iter.space_iter = Some(it);
Some(Box::new(iter))
},
None => None,
}
}
}

impl<'a> Iterator for DynSpaceIter<'a> {
type Item=&'a Atom;

fn next(&mut self) -> Option<Self::Item> {
self.space_iter.as_mut().unwrap().next()
}
}

impl PartialEq for DynSpace {
fn eq(&self, other: &Self) -> bool {
std::ptr::addr_eq(RefCell::as_ptr(&self.0), RefCell::as_ptr(&other.0))
Expand Down

0 comments on commit ab9c0c1

Please sign in to comment.