Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. use std::sync::{Arc, Mutex, Once};
  2.  
  3. trait Doot {
  4. fn new(name: String) -> Self;
  5. }
  6.  
  7. struct Birb {
  8. name: String,
  9. }
  10.  
  11. impl Drop for Birb {
  12. fn drop(&mut self) {
  13. // This should happen
  14. println!("Dropping {}", self.name);
  15. }
  16. }
  17.  
  18. struct CountedOption<T> {
  19. count: usize,
  20. value: Option<T>,
  21. }
  22.  
  23. impl<T> CountedOption<T> {
  24. fn empty() -> Self {
  25. CountedOption {
  26. count: 0,
  27. value: None,
  28. }
  29. }
  30. }
  31.  
  32. impl Doot for Birb {
  33. fn new(name: String) -> Self {
  34. Birb { name }
  35. }
  36. }
  37.  
  38. lazy_static::lazy_static! {
  39. static ref BIRB_MUTEX: Arc<Mutex<CountedOption<Birb>>> = Arc::new(Mutex::new(CountedOption::empty()));
  40. }
  41.  
  42. static INIT: Once = Once::new();
  43.  
  44. struct BirbMutex {
  45. inner: Arc<Mutex<CountedOption<Birb>>>,
  46. }
  47.  
  48. impl Doot for BirbMutex {
  49. fn new(name: String) -> Self {
  50. let mut co = BIRB_MUTEX
  51. .lock()
  52. .unwrap();
  53. if co.count == 0 {
  54. co
  55. .value
  56. .replace(Birb::new(name));
  57. }
  58. co.count += 1;
  59. BirbMutex {
  60. inner: BIRB_MUTEX.clone(),
  61. }
  62. }
  63. }
  64.  
  65. impl Drop for BirbMutex {
  66. fn drop(&mut self) {
  67. let mut co = self.inner.lock().unwrap();
  68. co.count -= 1;
  69. println!("{}", co.count);
  70. if co.count == 0 {
  71. co.value = None;
  72. }
  73. }
  74. }
  75.  
  76. fn foo() {
  77. let x1 = BirbMutex::new("George".to_string());
  78. let x2 = BirbMutex::new("Fred".to_string());
  79. }
  80. fn main() {
  81. foo();
  82. let x3 = BirbMutex::new("Hans".to_string());
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement