File tree Expand file tree Collapse file tree 1 file changed +14
-7
lines changed Expand file tree Collapse file tree 1 file changed +14
-7
lines changed Original file line number Diff line number Diff line change 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 ) ]
4550pub 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 ) ]
5057pub struct ObjectStore {
51- all_objects : Vec < Object > ,
58+ all_objects : HashMap < ObjectRef , Object > ,
5259}
5360
5461impl 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}
You can’t perform that action at this time.
0 commit comments