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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
use crate::data::arena::Index;
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[derive(Clone, Debug)]
/// A container for data associated to item existing into another Arena.
pub struct Coarena<T> {
data: Vec<(u64, T)>,
}
impl<T> Coarena<T> {
/// A coarena with no element.
pub fn new() -> Self {
Self { data: Vec::new() }
}
/// Gets a specific element from the coarena, if it exists.
pub fn get(&self, index: Index) -> Option<&T> {
let (i, g) = index.into_raw_parts();
self.data
.get(i)
.and_then(|(gg, t)| if g == *gg { Some(t) } else { None })
}
/// Gets a mutable reference to a specific element from the coarena, if it exists.
pub fn get_mut(&mut self, index: Index) -> Option<&mut T> {
let (i, g) = index.into_raw_parts();
self.data
.get_mut(i)
.and_then(|(gg, t)| if g == *gg { Some(t) } else { None })
}
pub fn ensure_element_exists(&mut self, index: Index, default: T) -> &mut T
where
T: Clone,
{
let (i1, g1) = index.into_raw_parts();
let elt1 = {
if self.data.len() <= i1 {
self.data.resize(i1 + 1, (u32::MAX as u64, default.clone()));
}
&mut self.data[i1]
};
if elt1.0 != g1 {
*elt1 = (g1, default);
}
&mut elt1.1
}
/// Ensure that elements at the two given indices exist in this coarena, and return their reference.
///
/// Missing elements are created automatically and initialized with the `default` value.
pub fn ensure_pair_exists(&mut self, a: Index, b: Index, default: T) -> (&mut T, &mut T)
where
T: Clone,
{
let (i1, g1) = a.into_raw_parts();
let (i2, g2) = b.into_raw_parts();
assert_ne!(i1, i2, "Cannot index the same object twice.");
let (elt1, elt2) = if i1 > i2 {
if self.data.len() <= i1 {
self.data.resize(i1 + 1, (u32::MAX as u64, default.clone()));
}
let (left, right) = self.data.split_at_mut(i1);
(&mut right[0], &mut left[i2])
} else {
// i2 > i1
if self.data.len() <= i2 {
self.data.resize(i2 + 1, (u32::MAX as u64, default.clone()));
}
let (left, right) = self.data.split_at_mut(i2);
(&mut left[i1], &mut right[0])
};
if elt1.0 != g1 {
*elt1 = (g1, default.clone());
}
if elt2.0 != g2 {
*elt2 = (g2, default);
}
(&mut elt1.1, &mut elt2.1)
}
}
impl<T> std::ops::Index<Index> for Coarena<T> {
type Output = T;
fn index(&self, id: Index) -> &T {
self.get(id).expect("Index out of bounds.")
}
}
impl<T> std::ops::IndexMut<Index> for Coarena<T> {
fn index_mut(&mut self, id: Index) -> &mut T {
self.get_mut(id).expect("Index out of bounds.")
}
}
|