1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use edge::Edge;
use vert::Vert;
use face::Face;
pub type EdgePtr = Ptr<Edge>;
pub type EdgeRc = Rc<RefCell<Edge>>;
pub type VertPtr = Ptr<Vert>;
pub type VertRc = Rc<RefCell<Vert>>;
pub type FacePtr = Ptr<Face>;
pub type FaceRc = Rc<RefCell<Face>>;
pub type RcRef<T> = Rc<RefCell<T>>;
#[derive(Debug)]
pub struct Ptr<T> {
val: Option<Weak<RefCell<T>>>
}
impl<T> Ptr<T> {
pub fn new_rc(val: T) -> Rc<RefCell<T>> { Rc::new(RefCell::new(val)) }
pub fn new(val: & Rc<RefCell<T>>) -> Ptr<T> {
Ptr { val: Some(Rc::downgrade(val)) }
}
pub fn empty() -> Ptr<T> {
Ptr { val: None }
}
pub fn merge_upgrade(weak_a: & Ptr<T>, weak_b: & Ptr<T>) -> Option<(RcRef<T>, RcRef<T>)> {
match (weak_a.upgrade(), weak_b.upgrade()) {
(Some(strong_a), Some(strong_b)) => Some((strong_a, strong_b)),
_ => None
}
}
pub fn is_valid(& self) -> bool { self.val.is_some() && self.upgrade().is_some() }
pub fn upgrade(& self) -> Option<Rc<RefCell<T>>> {
self.val.as_ref().and_then(|v| v.upgrade())
}
pub fn as_ref(& self) -> Option<& Weak<RefCell<T>>> {
self.val.as_ref()
}
}
impl<T> Clone for Ptr<T> {
fn clone(& self) -> Self {
Ptr { val: self.val.clone() }
}
}