reference_counting.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. use generational_box::{Storage, SyncStorage, UnsyncStorage};
  2. #[test]
  3. fn reference_counting() {
  4. fn reference_counting<S: Storage<String>>() {
  5. let data = String::from("hello world");
  6. let reference;
  7. {
  8. let outer_owner = S::owner();
  9. {
  10. // create an owner
  11. let owner = S::owner();
  12. // insert data into the store
  13. let original = owner.insert_rc(data);
  14. reference = outer_owner.insert_reference(original).unwrap();
  15. // The reference should point to the value immediately
  16. assert_eq!(&*reference.read(), "hello world");
  17. // Original is dropped
  18. }
  19. // The reference should still point to the value
  20. assert_eq!(&*reference.read(), "hello world");
  21. }
  22. // Now that all references are dropped, the value should be dropped
  23. assert!(reference.try_read().is_err());
  24. }
  25. reference_counting::<UnsyncStorage>();
  26. reference_counting::<SyncStorage>();
  27. }
  28. #[test]
  29. fn move_reference_in_place() {
  30. fn move_reference_in_place<S: Storage<String>>() {
  31. let data1 = String::from("hello world");
  32. let data2 = String::from("hello world 2");
  33. // create an owner
  34. let original_owner = S::owner();
  35. // insert data into the store
  36. let original = original_owner.insert_rc(data1.clone());
  37. let reference = original_owner.insert_reference(original).unwrap();
  38. // The reference should point to the original value
  39. assert_eq!(&*reference.read(), &data1);
  40. let new_owner = S::owner();
  41. // Move the reference in place
  42. let new = new_owner.insert_rc(data2.clone());
  43. reference.point_to(new).unwrap();
  44. // The reference should point to the new value
  45. assert_eq!(&*reference.read(), &data2);
  46. // make sure both got dropped
  47. drop(original_owner);
  48. drop(new_owner);
  49. assert!(original.try_read().is_err());
  50. assert!(new.try_read().is_err());
  51. }
  52. move_reference_in_place::<UnsyncStorage>();
  53. move_reference_in_place::<SyncStorage>();
  54. }