Skip to content

Commit 2d7f176

Browse files
committed
Use globally unique ids instead of local vector indexes for object references.
1 parent 7f979c4 commit 2d7f176

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/objects/mod.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use std::collections::HashSet;
1+
use std::collections::HashMap;
2+
use std::sync::Mutex;
3+
use std::sync::atomic::{AtomicUsize, Ordering};
24

35
#[derive(Debug)]
46
#[derive(Clone)]
@@ -41,29 +43,34 @@ pub struct Object {
4143
}
4244

4345
#[derive(Debug)]
46+
#[derive(Hash)]
4447
#[derive(Clone)]
48+
#[derive(Eq)]
49+
#[derive(PartialEq)]
4550
pub struct ObjectRef {
46-
index: usize,
51+
id: usize,
4752
}
4853

54+
static current_ref_id: AtomicUsize = ::std::sync::atomic::ATOMIC_USIZE_INIT;
55+
4956
#[derive(Debug)]
5057
pub struct ObjectStore {
51-
all_objects: Vec<Object>,
58+
all_objects: HashMap<ObjectRef, Object>,
5259
}
5360

5461
impl ObjectStore {
5562
pub fn new() -> ObjectStore {
56-
ObjectStore { all_objects: Vec::new() }
63+
ObjectStore { all_objects: HashMap::new() }
5764
}
5865

5966
pub fn allocate(&mut self, obj: ObjectContent) -> ObjectRef {
60-
let obj_ref = ObjectRef { index: self.all_objects.len() };
61-
self.all_objects.push(Object { content: obj });
67+
let obj_ref = ObjectRef { id: current_ref_id.fetch_add(1, Ordering::SeqCst) };
68+
self.all_objects.insert(obj_ref.clone(), Object { content: obj });
6269
obj_ref
6370
}
6471

6572
pub fn deref(&self, obj_ref: &ObjectRef) -> &Object {
6673
// TODO: check the reference is valid
67-
self.all_objects.get(obj_ref.index).unwrap()
74+
self.all_objects.get(obj_ref).unwrap()
6875
}
6976
}

0 commit comments

Comments
 (0)