Show More
@@ -57,26 +57,6 b' struct PySharedState {' | |||
|
57 | 57 | } |
|
58 | 58 | |
|
59 | 59 | impl PySharedState { |
|
60 | fn try_borrow_mut<'a, T>( | |
|
61 | &'a self, | |
|
62 | py: Python<'a>, | |
|
63 | pyrefmut: RefMut<'a, T>, | |
|
64 | ) -> PyResult<RefMut<'a, T>> { | |
|
65 | match self.current_borrow_count(py) { | |
|
66 | 0 => { | |
|
67 | // Note that this wraps around to the same value if mutably | |
|
68 | // borrowed more than usize::MAX times, which wouldn't happen | |
|
69 | // in practice. | |
|
70 | self.generation.fetch_add(1, Ordering::Relaxed); | |
|
71 | Ok(pyrefmut) | |
|
72 | } | |
|
73 | _ => Err(AlreadyBorrowed::new( | |
|
74 | py, | |
|
75 | "Cannot borrow mutably while immutably borrowed", | |
|
76 | )), | |
|
77 | } | |
|
78 | } | |
|
79 | ||
|
80 | 60 | /// Return a reference to the wrapped data and its state with an |
|
81 | 61 | /// artificial static lifetime. |
|
82 | 62 | /// We need to be protected by the GIL for thread-safety. |
@@ -113,6 +93,14 b' impl PySharedState {' | |||
|
113 | 93 | fn current_generation(&self, _py: Python) -> usize { |
|
114 | 94 | self.generation.load(Ordering::Relaxed) |
|
115 | 95 | } |
|
96 | ||
|
97 | fn increment_generation(&self, py: Python) { | |
|
98 | assert_eq!(self.current_borrow_count(py), 0); | |
|
99 | // Note that this wraps around to the same value if mutably | |
|
100 | // borrowed more than usize::MAX times, which wouldn't happen | |
|
101 | // in practice. | |
|
102 | self.generation.fetch_add(1, Ordering::Relaxed); | |
|
103 | } | |
|
116 | 104 | } |
|
117 | 105 | |
|
118 | 106 | /// Helper to keep the borrow count updated while the shared object is |
@@ -170,11 +158,18 b' impl<T> PySharedRefCell<T> {' | |||
|
170 | 158 | &'a self, |
|
171 | 159 | py: Python<'a>, |
|
172 | 160 | ) -> PyResult<RefMut<'a, T>> { |
|
161 | if self.py_shared_state.current_borrow_count(py) > 0 { | |
|
162 | return Err(AlreadyBorrowed::new( | |
|
163 | py, | |
|
164 | "Cannot borrow mutably while immutably borrowed", | |
|
165 | )); | |
|
166 | } | |
|
173 | 167 | let inner_ref = self |
|
174 | 168 | .inner |
|
175 | 169 | .try_borrow_mut() |
|
176 | 170 | .map_err(|e| AlreadyBorrowed::new(py, e.to_string()))?; |
|
177 |
self.py_shared_state. |
|
|
171 | self.py_shared_state.increment_generation(py); | |
|
172 | Ok(inner_ref) | |
|
178 | 173 | } |
|
179 | 174 | } |
|
180 | 175 |
General Comments 0
You need to be logged in to leave comments.
Login now