##// END OF EJS Templates
rust-cpython: leverage RefCell::borrow() to guarantee there's no mutable ref...
Yuya Nishihara -
r43608:b7ab3a0a default
parent child Browse files
Show More
@@ -1,705 +1,717 b''
1 // ref_sharing.rs
1 // ref_sharing.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to
6 // of this software and associated documentation files (the "Software"), to
7 // deal in the Software without restriction, including without limitation the
7 // deal in the Software without restriction, including without limitation the
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 // sell copies of the Software, and to permit persons to whom the Software is
9 // sell copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
10 // furnished to do so, subject to the following conditions:
11 //
11 //
12 // The above copyright notice and this permission notice shall be included in
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
13 // all copies or substantial portions of the Software.
14 //
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 // IN THE SOFTWARE.
21 // IN THE SOFTWARE.
22
22
23 //! Macros for use in the `hg-cpython` bridge library.
23 //! Macros for use in the `hg-cpython` bridge library.
24
24
25 use crate::exceptions::AlreadyBorrowed;
25 use crate::exceptions::AlreadyBorrowed;
26 use cpython::{exc, PyClone, PyErr, PyObject, PyResult, Python};
26 use cpython::{exc, PyClone, PyErr, PyObject, PyResult, Python};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
27 use std::cell::{Cell, Ref, RefCell, RefMut};
28 use std::ops::{Deref, DerefMut};
28 use std::ops::{Deref, DerefMut};
29 use std::sync::atomic::{AtomicUsize, Ordering};
29 use std::sync::atomic::{AtomicUsize, Ordering};
30
30
31 /// Manages the shared state between Python and Rust
31 /// Manages the shared state between Python and Rust
32 ///
32 ///
33 /// `PySharedState` is owned by `PySharedRefCell`, and is shared across its
33 /// `PySharedState` is owned by `PySharedRefCell`, and is shared across its
34 /// derived references. The consistency of these references are guaranteed
34 /// derived references. The consistency of these references are guaranteed
35 /// as follows:
35 /// as follows:
36 ///
36 ///
37 /// - The immutability of `py_class!` object fields. Any mutation of
37 /// - The immutability of `py_class!` object fields. Any mutation of
38 /// `PySharedRefCell` is allowed only through its `borrow_mut()`.
38 /// `PySharedRefCell` is allowed only through its `borrow_mut()`.
39 /// - The `py: Python<'_>` token, which makes sure that any data access is
39 /// - The `py: Python<'_>` token, which makes sure that any data access is
40 /// synchronized by the GIL.
40 /// synchronized by the GIL.
41 /// - The underlying `RefCell`, which prevents `PySharedRefCell` data from
42 /// being directly borrowed or leaked while it is mutably borrowed.
41 /// - The `borrow_count`, which is the number of references borrowed from
43 /// - The `borrow_count`, which is the number of references borrowed from
42 /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked`
44 /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked`
43 /// is borrowed.
45 /// is borrowed.
44 /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked`
46 /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked`
45 /// reference is valid only if the `current_generation()` equals to the
47 /// reference is valid only if the `current_generation()` equals to the
46 /// `generation` at the time of `leak_immutable()`.
48 /// `generation` at the time of `leak_immutable()`.
47 #[derive(Debug, Default)]
49 #[derive(Debug, Default)]
48 struct PySharedState {
50 struct PySharedState {
49 mutably_borrowed: Cell<bool>,
51 mutably_borrowed: Cell<bool>,
50 // The counter variable could be Cell<usize> since any operation on
52 // The counter variable could be Cell<usize> since any operation on
51 // PySharedState is synchronized by the GIL, but being "atomic" makes
53 // PySharedState is synchronized by the GIL, but being "atomic" makes
52 // PySharedState inherently Sync. The ordering requirement doesn't
54 // PySharedState inherently Sync. The ordering requirement doesn't
53 // matter thanks to the GIL.
55 // matter thanks to the GIL.
54 borrow_count: AtomicUsize,
56 borrow_count: AtomicUsize,
55 generation: AtomicUsize,
57 generation: AtomicUsize,
56 }
58 }
57
59
58 // &PySharedState can be Send because any access to inner cells is
60 // &PySharedState can be Send because any access to inner cells is
59 // synchronized by the GIL.
61 // synchronized by the GIL.
60 unsafe impl Sync for PySharedState {}
62 unsafe impl Sync for PySharedState {}
61
63
62 impl PySharedState {
64 impl PySharedState {
63 fn borrow_mut<'a, T>(
65 fn borrow_mut<'a, T>(
64 &'a self,
66 &'a self,
65 py: Python<'a>,
67 py: Python<'a>,
66 pyrefmut: RefMut<'a, T>,
68 pyrefmut: RefMut<'a, T>,
67 ) -> PyResult<PyRefMut<'a, T>> {
69 ) -> PyResult<PyRefMut<'a, T>> {
68 if self.mutably_borrowed.get() {
70 if self.mutably_borrowed.get() {
69 return Err(AlreadyBorrowed::new(
71 return Err(AlreadyBorrowed::new(
70 py,
72 py,
71 "Cannot borrow mutably while there exists another \
73 "Cannot borrow mutably while there exists another \
72 mutable reference in a Python object",
74 mutable reference in a Python object",
73 ));
75 ));
74 }
76 }
75 match self.current_borrow_count(py) {
77 match self.current_borrow_count(py) {
76 0 => {
78 0 => {
77 self.mutably_borrowed.replace(true);
79 self.mutably_borrowed.replace(true);
78 // Note that this wraps around to the same value if mutably
80 // Note that this wraps around to the same value if mutably
79 // borrowed more than usize::MAX times, which wouldn't happen
81 // borrowed more than usize::MAX times, which wouldn't happen
80 // in practice.
82 // in practice.
81 self.generation.fetch_add(1, Ordering::Relaxed);
83 self.generation.fetch_add(1, Ordering::Relaxed);
82 Ok(PyRefMut::new(py, pyrefmut, self))
84 Ok(PyRefMut::new(py, pyrefmut, self))
83 }
85 }
84 _ => Err(AlreadyBorrowed::new(
86 _ => Err(AlreadyBorrowed::new(
85 py,
87 py,
86 "Cannot borrow mutably while immutably borrowed",
88 "Cannot borrow mutably while immutably borrowed",
87 )),
89 )),
88 }
90 }
89 }
91 }
90
92
91 /// Return a reference to the wrapped data and its state with an
93 /// Return a reference to the wrapped data and its state with an
92 /// artificial static lifetime.
94 /// artificial static lifetime.
93 /// We need to be protected by the GIL for thread-safety.
95 /// We need to be protected by the GIL for thread-safety.
94 ///
96 ///
95 /// # Safety
97 /// # Safety
96 ///
98 ///
97 /// This is highly unsafe since the lifetime of the given data can be
99 /// This is highly unsafe since the lifetime of the given data can be
98 /// extended. Do not call this function directly.
100 /// extended. Do not call this function directly.
99 unsafe fn leak_immutable<T>(
101 unsafe fn leak_immutable<T>(
100 &self,
102 &self,
101 py: Python,
103 py: Python,
102 data: &PySharedRefCell<T>,
104 data: Ref<T>,
103 ) -> PyResult<(&'static T, &'static PySharedState)> {
105 ) -> PyResult<(&'static T, &'static PySharedState)> {
104 if self.mutably_borrowed.get() {
106 if self.mutably_borrowed.get() {
105 return Err(AlreadyBorrowed::new(
107 return Err(AlreadyBorrowed::new(
106 py,
108 py,
107 "Cannot borrow immutably while there is a \
109 "Cannot borrow immutably while there is a \
108 mutable reference in Python objects",
110 mutable reference in Python objects",
109 ));
111 ));
110 }
112 }
111 // TODO: it's weird that self is data.py_shared_state. Maybe we
113 let ptr: *const T = &*data;
112 // can move stuff to PySharedRefCell?
114 let state_ptr: *const PySharedState = self;
113 let ptr = data.as_ptr();
114 let state_ptr: *const PySharedState = &data.py_shared_state;
115 Ok((&*ptr, &*state_ptr))
115 Ok((&*ptr, &*state_ptr))
116 }
116 }
117
117
118 fn current_borrow_count(&self, _py: Python) -> usize {
118 fn current_borrow_count(&self, _py: Python) -> usize {
119 self.borrow_count.load(Ordering::Relaxed)
119 self.borrow_count.load(Ordering::Relaxed)
120 }
120 }
121
121
122 fn increase_borrow_count(&self, _py: Python) {
122 fn increase_borrow_count(&self, _py: Python) {
123 // Note that this wraps around if there are more than usize::MAX
123 // Note that this wraps around if there are more than usize::MAX
124 // borrowed references, which shouldn't happen due to memory limit.
124 // borrowed references, which shouldn't happen due to memory limit.
125 self.borrow_count.fetch_add(1, Ordering::Relaxed);
125 self.borrow_count.fetch_add(1, Ordering::Relaxed);
126 }
126 }
127
127
128 fn decrease_borrow_count(&self, _py: Python) {
128 fn decrease_borrow_count(&self, _py: Python) {
129 let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed);
129 let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed);
130 assert!(prev_count > 0);
130 assert!(prev_count > 0);
131 }
131 }
132
132
133 /// # Safety
133 /// # Safety
134 ///
134 ///
135 /// It's up to you to make sure the reference is about to be deleted
135 /// It's up to you to make sure the reference is about to be deleted
136 /// when updating the leak count.
136 /// when updating the leak count.
137 fn decrease_leak_count(&self, py: Python, mutable: bool) {
137 fn decrease_leak_count(&self, py: Python, mutable: bool) {
138 if mutable {
138 if mutable {
139 assert_eq!(self.current_borrow_count(py), 0);
139 assert_eq!(self.current_borrow_count(py), 0);
140 assert!(self.mutably_borrowed.get());
140 assert!(self.mutably_borrowed.get());
141 self.mutably_borrowed.replace(false);
141 self.mutably_borrowed.replace(false);
142 } else {
142 } else {
143 unimplemented!();
143 unimplemented!();
144 }
144 }
145 }
145 }
146
146
147 fn current_generation(&self, _py: Python) -> usize {
147 fn current_generation(&self, _py: Python) -> usize {
148 self.generation.load(Ordering::Relaxed)
148 self.generation.load(Ordering::Relaxed)
149 }
149 }
150 }
150 }
151
151
152 /// Helper to keep the borrow count updated while the shared object is
152 /// Helper to keep the borrow count updated while the shared object is
153 /// immutably borrowed without using the `RefCell` interface.
153 /// immutably borrowed without using the `RefCell` interface.
154 struct BorrowPyShared<'a> {
154 struct BorrowPyShared<'a> {
155 py: Python<'a>,
155 py: Python<'a>,
156 py_shared_state: &'a PySharedState,
156 py_shared_state: &'a PySharedState,
157 }
157 }
158
158
159 impl<'a> BorrowPyShared<'a> {
159 impl<'a> BorrowPyShared<'a> {
160 fn new(
160 fn new(
161 py: Python<'a>,
161 py: Python<'a>,
162 py_shared_state: &'a PySharedState,
162 py_shared_state: &'a PySharedState,
163 ) -> BorrowPyShared<'a> {
163 ) -> BorrowPyShared<'a> {
164 py_shared_state.increase_borrow_count(py);
164 py_shared_state.increase_borrow_count(py);
165 BorrowPyShared {
165 BorrowPyShared {
166 py,
166 py,
167 py_shared_state,
167 py_shared_state,
168 }
168 }
169 }
169 }
170 }
170 }
171
171
172 impl Drop for BorrowPyShared<'_> {
172 impl Drop for BorrowPyShared<'_> {
173 fn drop(&mut self) {
173 fn drop(&mut self) {
174 self.py_shared_state.decrease_borrow_count(self.py);
174 self.py_shared_state.decrease_borrow_count(self.py);
175 }
175 }
176 }
176 }
177
177
178 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
178 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
179 ///
179 ///
180 /// This object can be stored in a `py_class!` object as a data field. Any
180 /// This object can be stored in a `py_class!` object as a data field. Any
181 /// operation is allowed through the `PySharedRef` interface.
181 /// operation is allowed through the `PySharedRef` interface.
182 #[derive(Debug)]
182 #[derive(Debug)]
183 pub struct PySharedRefCell<T> {
183 pub struct PySharedRefCell<T> {
184 inner: RefCell<T>,
184 inner: RefCell<T>,
185 py_shared_state: PySharedState,
185 py_shared_state: PySharedState,
186 }
186 }
187
187
188 impl<T> PySharedRefCell<T> {
188 impl<T> PySharedRefCell<T> {
189 pub fn new(value: T) -> PySharedRefCell<T> {
189 pub fn new(value: T) -> PySharedRefCell<T> {
190 Self {
190 Self {
191 inner: RefCell::new(value),
191 inner: RefCell::new(value),
192 py_shared_state: PySharedState::default(),
192 py_shared_state: PySharedState::default(),
193 }
193 }
194 }
194 }
195
195
196 fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> {
196 fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> {
197 // py_shared_state isn't involved since
197 // py_shared_state isn't involved since
198 // - inner.borrow() would fail if self is mutably borrowed,
198 // - inner.borrow() would fail if self is mutably borrowed,
199 // - and inner.borrow_mut() would fail while self is borrowed.
199 // - and inner.borrow_mut() would fail while self is borrowed.
200 self.inner.borrow()
200 self.inner.borrow()
201 }
201 }
202
202
203 fn as_ptr(&self) -> *mut T {
204 self.inner.as_ptr()
205 }
206
207 // TODO: maybe this should be named as try_borrow_mut(), and use
203 // TODO: maybe this should be named as try_borrow_mut(), and use
208 // inner.try_borrow_mut(). The current implementation panics if
204 // inner.try_borrow_mut(). The current implementation panics if
209 // self.inner has been borrowed, but returns error if py_shared_state
205 // self.inner has been borrowed, but returns error if py_shared_state
210 // refuses to borrow.
206 // refuses to borrow.
211 fn borrow_mut<'a>(&'a self, py: Python<'a>) -> PyResult<PyRefMut<'a, T>> {
207 fn borrow_mut<'a>(&'a self, py: Python<'a>) -> PyResult<PyRefMut<'a, T>> {
212 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
208 self.py_shared_state.borrow_mut(py, self.inner.borrow_mut())
213 }
209 }
214 }
210 }
215
211
216 /// Sharable data member of type `T` borrowed from the `PyObject`.
212 /// Sharable data member of type `T` borrowed from the `PyObject`.
217 pub struct PySharedRef<'a, T> {
213 pub struct PySharedRef<'a, T> {
218 py: Python<'a>,
214 py: Python<'a>,
219 owner: &'a PyObject,
215 owner: &'a PyObject,
220 data: &'a PySharedRefCell<T>,
216 data: &'a PySharedRefCell<T>,
221 }
217 }
222
218
223 impl<'a, T> PySharedRef<'a, T> {
219 impl<'a, T> PySharedRef<'a, T> {
224 /// # Safety
220 /// # Safety
225 ///
221 ///
226 /// The `data` must be owned by the `owner`. Otherwise, the leak count
222 /// The `data` must be owned by the `owner`. Otherwise, the leak count
227 /// would get wrong.
223 /// would get wrong.
228 pub unsafe fn new(
224 pub unsafe fn new(
229 py: Python<'a>,
225 py: Python<'a>,
230 owner: &'a PyObject,
226 owner: &'a PyObject,
231 data: &'a PySharedRefCell<T>,
227 data: &'a PySharedRefCell<T>,
232 ) -> Self {
228 ) -> Self {
233 Self { py, owner, data }
229 Self { py, owner, data }
234 }
230 }
235
231
236 pub fn borrow(&self) -> Ref<'a, T> {
232 pub fn borrow(&self) -> Ref<'a, T> {
237 self.data.borrow(self.py)
233 self.data.borrow(self.py)
238 }
234 }
239
235
240 pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> {
236 pub fn borrow_mut(&self) -> PyResult<PyRefMut<'a, T>> {
241 self.data.borrow_mut(self.py)
237 self.data.borrow_mut(self.py)
242 }
238 }
243
239
244 /// Returns a leaked reference.
240 /// Returns a leaked reference.
241 ///
242 /// # Panics
243 ///
244 /// Panics if this is mutably borrowed.
245 pub fn leak_immutable(&self) -> PyResult<PyLeaked<&'static T>> {
245 pub fn leak_immutable(&self) -> PyResult<PyLeaked<&'static T>> {
246 let state = &self.data.py_shared_state;
246 let state = &self.data.py_shared_state;
247 // make sure self.data isn't mutably borrowed; otherwise the
248 // generation number can't be trusted.
249 let data_ref = self.borrow();
247 unsafe {
250 unsafe {
248 let (static_ref, static_state_ref) =
251 let (static_ref, static_state_ref) =
249 state.leak_immutable(self.py, self.data)?;
252 state.leak_immutable(self.py, data_ref)?;
250 Ok(PyLeaked::new(
253 Ok(PyLeaked::new(
251 self.py,
254 self.py,
252 self.owner,
255 self.owner,
253 static_ref,
256 static_ref,
254 static_state_ref,
257 static_state_ref,
255 ))
258 ))
256 }
259 }
257 }
260 }
258 }
261 }
259
262
260 /// Holds a mutable reference to data shared between Python and Rust.
263 /// Holds a mutable reference to data shared between Python and Rust.
261 pub struct PyRefMut<'a, T> {
264 pub struct PyRefMut<'a, T> {
262 py: Python<'a>,
265 py: Python<'a>,
263 inner: RefMut<'a, T>,
266 inner: RefMut<'a, T>,
264 py_shared_state: &'a PySharedState,
267 py_shared_state: &'a PySharedState,
265 }
268 }
266
269
267 impl<'a, T> PyRefMut<'a, T> {
270 impl<'a, T> PyRefMut<'a, T> {
268 // Must be constructed by PySharedState after checking its leak_count.
271 // Must be constructed by PySharedState after checking its leak_count.
269 // Otherwise, drop() would incorrectly update the state.
272 // Otherwise, drop() would incorrectly update the state.
270 fn new(
273 fn new(
271 py: Python<'a>,
274 py: Python<'a>,
272 inner: RefMut<'a, T>,
275 inner: RefMut<'a, T>,
273 py_shared_state: &'a PySharedState,
276 py_shared_state: &'a PySharedState,
274 ) -> Self {
277 ) -> Self {
275 Self {
278 Self {
276 py,
279 py,
277 inner,
280 inner,
278 py_shared_state,
281 py_shared_state,
279 }
282 }
280 }
283 }
281 }
284 }
282
285
283 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
286 impl<'a, T> std::ops::Deref for PyRefMut<'a, T> {
284 type Target = RefMut<'a, T>;
287 type Target = RefMut<'a, T>;
285
288
286 fn deref(&self) -> &Self::Target {
289 fn deref(&self) -> &Self::Target {
287 &self.inner
290 &self.inner
288 }
291 }
289 }
292 }
290 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
293 impl<'a, T> std::ops::DerefMut for PyRefMut<'a, T> {
291 fn deref_mut(&mut self) -> &mut Self::Target {
294 fn deref_mut(&mut self) -> &mut Self::Target {
292 &mut self.inner
295 &mut self.inner
293 }
296 }
294 }
297 }
295
298
296 impl<'a, T> Drop for PyRefMut<'a, T> {
299 impl<'a, T> Drop for PyRefMut<'a, T> {
297 fn drop(&mut self) {
300 fn drop(&mut self) {
298 self.py_shared_state.decrease_leak_count(self.py, true);
301 self.py_shared_state.decrease_leak_count(self.py, true);
299 }
302 }
300 }
303 }
301
304
302 /// Allows a `py_class!` generated struct to share references to one of its
305 /// Allows a `py_class!` generated struct to share references to one of its
303 /// data members with Python.
306 /// data members with Python.
304 ///
307 ///
305 /// # Parameters
308 /// # Parameters
306 ///
309 ///
307 /// * `$name` is the same identifier used in for `py_class!` macro call.
310 /// * `$name` is the same identifier used in for `py_class!` macro call.
308 /// * `$inner_struct` is the identifier of the underlying Rust struct
311 /// * `$inner_struct` is the identifier of the underlying Rust struct
309 /// * `$data_member` is the identifier of the data member of `$inner_struct`
312 /// * `$data_member` is the identifier of the data member of `$inner_struct`
310 /// that will be shared.
313 /// that will be shared.
311 /// * `$shared_accessor` is the function name to be generated, which allows
314 /// * `$shared_accessor` is the function name to be generated, which allows
312 /// safe access to the data member.
315 /// safe access to the data member.
313 ///
316 ///
314 /// # Safety
317 /// # Safety
315 ///
318 ///
316 /// `$data_member` must persist while the `$name` object is alive. In other
319 /// `$data_member` must persist while the `$name` object is alive. In other
317 /// words, it must be an accessor to a data field of the Python object.
320 /// words, it must be an accessor to a data field of the Python object.
318 ///
321 ///
319 /// # Example
322 /// # Example
320 ///
323 ///
321 /// ```
324 /// ```
322 /// struct MyStruct {
325 /// struct MyStruct {
323 /// inner: Vec<u32>;
326 /// inner: Vec<u32>;
324 /// }
327 /// }
325 ///
328 ///
326 /// py_class!(pub class MyType |py| {
329 /// py_class!(pub class MyType |py| {
327 /// data inner: PySharedRefCell<MyStruct>;
330 /// data inner: PySharedRefCell<MyStruct>;
328 /// });
331 /// });
329 ///
332 ///
330 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
333 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
331 /// ```
334 /// ```
332 macro_rules! py_shared_ref {
335 macro_rules! py_shared_ref {
333 (
336 (
334 $name: ident,
337 $name: ident,
335 $inner_struct: ident,
338 $inner_struct: ident,
336 $data_member: ident,
339 $data_member: ident,
337 $shared_accessor: ident
340 $shared_accessor: ident
338 ) => {
341 ) => {
339 impl $name {
342 impl $name {
340 /// Returns a safe reference to the shared `$data_member`.
343 /// Returns a safe reference to the shared `$data_member`.
341 ///
344 ///
342 /// This function guarantees that `PySharedRef` is created with
345 /// This function guarantees that `PySharedRef` is created with
343 /// the valid `self` and `self.$data_member(py)` pair.
346 /// the valid `self` and `self.$data_member(py)` pair.
344 fn $shared_accessor<'a>(
347 fn $shared_accessor<'a>(
345 &'a self,
348 &'a self,
346 py: Python<'a>,
349 py: Python<'a>,
347 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
350 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
348 use cpython::PythonObject;
351 use cpython::PythonObject;
349 use $crate::ref_sharing::PySharedRef;
352 use $crate::ref_sharing::PySharedRef;
350 let owner = self.as_object();
353 let owner = self.as_object();
351 let data = self.$data_member(py);
354 let data = self.$data_member(py);
352 unsafe { PySharedRef::new(py, owner, data) }
355 unsafe { PySharedRef::new(py, owner, data) }
353 }
356 }
354 }
357 }
355 };
358 };
356 }
359 }
357
360
358 /// Manage immutable references to `PyObject` leaked into Python iterators.
361 /// Manage immutable references to `PyObject` leaked into Python iterators.
359 ///
362 ///
360 /// This reference will be invalidated once the original value is mutably
363 /// This reference will be invalidated once the original value is mutably
361 /// borrowed.
364 /// borrowed.
362 pub struct PyLeaked<T> {
365 pub struct PyLeaked<T> {
363 inner: PyObject,
366 inner: PyObject,
364 data: Option<T>,
367 data: Option<T>,
365 py_shared_state: &'static PySharedState,
368 py_shared_state: &'static PySharedState,
366 /// Generation counter of data `T` captured when PyLeaked is created.
369 /// Generation counter of data `T` captured when PyLeaked is created.
367 generation: usize,
370 generation: usize,
368 }
371 }
369
372
370 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
373 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
371 // without taking Python GIL wouldn't be safe. Also, the underling reference
374 // without taking Python GIL wouldn't be safe. Also, the underling reference
372 // is invalid if generation != py_shared_state.generation.
375 // is invalid if generation != py_shared_state.generation.
373
376
374 impl<T> PyLeaked<T> {
377 impl<T> PyLeaked<T> {
375 /// # Safety
378 /// # Safety
376 ///
379 ///
377 /// The `py_shared_state` must be owned by the `inner` Python object.
380 /// The `py_shared_state` must be owned by the `inner` Python object.
378 fn new(
381 fn new(
379 py: Python,
382 py: Python,
380 inner: &PyObject,
383 inner: &PyObject,
381 data: T,
384 data: T,
382 py_shared_state: &'static PySharedState,
385 py_shared_state: &'static PySharedState,
383 ) -> Self {
386 ) -> Self {
384 Self {
387 Self {
385 inner: inner.clone_ref(py),
388 inner: inner.clone_ref(py),
386 data: Some(data),
389 data: Some(data),
387 py_shared_state,
390 py_shared_state,
388 generation: py_shared_state.current_generation(py),
391 generation: py_shared_state.current_generation(py),
389 }
392 }
390 }
393 }
391
394
392 /// Immutably borrows the wrapped value.
395 /// Immutably borrows the wrapped value.
393 ///
396 ///
394 /// Borrowing fails if the underlying reference has been invalidated.
397 /// Borrowing fails if the underlying reference has been invalidated.
395 pub fn try_borrow<'a>(
398 pub fn try_borrow<'a>(
396 &'a self,
399 &'a self,
397 py: Python<'a>,
400 py: Python<'a>,
398 ) -> PyResult<PyLeakedRef<'a, T>> {
401 ) -> PyResult<PyLeakedRef<'a, T>> {
399 self.validate_generation(py)?;
402 self.validate_generation(py)?;
400 Ok(PyLeakedRef {
403 Ok(PyLeakedRef {
401 _borrow: BorrowPyShared::new(py, self.py_shared_state),
404 _borrow: BorrowPyShared::new(py, self.py_shared_state),
402 data: self.data.as_ref().unwrap(),
405 data: self.data.as_ref().unwrap(),
403 })
406 })
404 }
407 }
405
408
406 /// Mutably borrows the wrapped value.
409 /// Mutably borrows the wrapped value.
407 ///
410 ///
408 /// Borrowing fails if the underlying reference has been invalidated.
411 /// Borrowing fails if the underlying reference has been invalidated.
409 ///
412 ///
410 /// Typically `T` is an iterator. If `T` is an immutable reference,
413 /// Typically `T` is an iterator. If `T` is an immutable reference,
411 /// `get_mut()` is useless since the inner value can't be mutated.
414 /// `get_mut()` is useless since the inner value can't be mutated.
412 pub fn try_borrow_mut<'a>(
415 pub fn try_borrow_mut<'a>(
413 &'a mut self,
416 &'a mut self,
414 py: Python<'a>,
417 py: Python<'a>,
415 ) -> PyResult<PyLeakedRefMut<'a, T>> {
418 ) -> PyResult<PyLeakedRefMut<'a, T>> {
416 self.validate_generation(py)?;
419 self.validate_generation(py)?;
417 Ok(PyLeakedRefMut {
420 Ok(PyLeakedRefMut {
418 _borrow: BorrowPyShared::new(py, self.py_shared_state),
421 _borrow: BorrowPyShared::new(py, self.py_shared_state),
419 data: self.data.as_mut().unwrap(),
422 data: self.data.as_mut().unwrap(),
420 })
423 })
421 }
424 }
422
425
423 /// Converts the inner value by the given function.
426 /// Converts the inner value by the given function.
424 ///
427 ///
425 /// Typically `T` is a static reference to a container, and `U` is an
428 /// Typically `T` is a static reference to a container, and `U` is an
426 /// iterator of that container.
429 /// iterator of that container.
427 ///
430 ///
428 /// # Panics
431 /// # Panics
429 ///
432 ///
430 /// Panics if the underlying reference has been invalidated.
433 /// Panics if the underlying reference has been invalidated.
431 ///
434 ///
432 /// This is typically called immediately after the `PyLeaked` is obtained.
435 /// This is typically called immediately after the `PyLeaked` is obtained.
433 /// In which case, the reference must be valid and no panic would occur.
436 /// In which case, the reference must be valid and no panic would occur.
434 ///
437 ///
435 /// # Safety
438 /// # Safety
436 ///
439 ///
437 /// The lifetime of the object passed in to the function `f` is cheated.
440 /// The lifetime of the object passed in to the function `f` is cheated.
438 /// It's typically a static reference, but is valid only while the
441 /// It's typically a static reference, but is valid only while the
439 /// corresponding `PyLeaked` is alive. Do not copy it out of the
442 /// corresponding `PyLeaked` is alive. Do not copy it out of the
440 /// function call.
443 /// function call.
441 pub unsafe fn map<U>(
444 pub unsafe fn map<U>(
442 mut self,
445 mut self,
443 py: Python,
446 py: Python,
444 f: impl FnOnce(T) -> U,
447 f: impl FnOnce(T) -> U,
445 ) -> PyLeaked<U> {
448 ) -> PyLeaked<U> {
446 // Needs to test the generation value to make sure self.data reference
449 // Needs to test the generation value to make sure self.data reference
447 // is still intact.
450 // is still intact.
448 self.validate_generation(py)
451 self.validate_generation(py)
449 .expect("map() over invalidated leaked reference");
452 .expect("map() over invalidated leaked reference");
450
453
451 // f() could make the self.data outlive. That's why map() is unsafe.
454 // f() could make the self.data outlive. That's why map() is unsafe.
452 // In order to make this function safe, maybe we'll need a way to
455 // In order to make this function safe, maybe we'll need a way to
453 // temporarily restrict the lifetime of self.data and translate the
456 // temporarily restrict the lifetime of self.data and translate the
454 // returned object back to Something<'static>.
457 // returned object back to Something<'static>.
455 let new_data = f(self.data.take().unwrap());
458 let new_data = f(self.data.take().unwrap());
456 PyLeaked {
459 PyLeaked {
457 inner: self.inner.clone_ref(py),
460 inner: self.inner.clone_ref(py),
458 data: Some(new_data),
461 data: Some(new_data),
459 py_shared_state: self.py_shared_state,
462 py_shared_state: self.py_shared_state,
460 generation: self.generation,
463 generation: self.generation,
461 }
464 }
462 }
465 }
463
466
464 fn validate_generation(&self, py: Python) -> PyResult<()> {
467 fn validate_generation(&self, py: Python) -> PyResult<()> {
465 if self.py_shared_state.current_generation(py) == self.generation {
468 if self.py_shared_state.current_generation(py) == self.generation {
466 Ok(())
469 Ok(())
467 } else {
470 } else {
468 Err(PyErr::new::<exc::RuntimeError, _>(
471 Err(PyErr::new::<exc::RuntimeError, _>(
469 py,
472 py,
470 "Cannot access to leaked reference after mutation",
473 "Cannot access to leaked reference after mutation",
471 ))
474 ))
472 }
475 }
473 }
476 }
474 }
477 }
475
478
476 /// Immutably borrowed reference to a leaked value.
479 /// Immutably borrowed reference to a leaked value.
477 pub struct PyLeakedRef<'a, T> {
480 pub struct PyLeakedRef<'a, T> {
478 _borrow: BorrowPyShared<'a>,
481 _borrow: BorrowPyShared<'a>,
479 data: &'a T,
482 data: &'a T,
480 }
483 }
481
484
482 impl<T> Deref for PyLeakedRef<'_, T> {
485 impl<T> Deref for PyLeakedRef<'_, T> {
483 type Target = T;
486 type Target = T;
484
487
485 fn deref(&self) -> &T {
488 fn deref(&self) -> &T {
486 self.data
489 self.data
487 }
490 }
488 }
491 }
489
492
490 /// Mutably borrowed reference to a leaked value.
493 /// Mutably borrowed reference to a leaked value.
491 pub struct PyLeakedRefMut<'a, T> {
494 pub struct PyLeakedRefMut<'a, T> {
492 _borrow: BorrowPyShared<'a>,
495 _borrow: BorrowPyShared<'a>,
493 data: &'a mut T,
496 data: &'a mut T,
494 }
497 }
495
498
496 impl<T> Deref for PyLeakedRefMut<'_, T> {
499 impl<T> Deref for PyLeakedRefMut<'_, T> {
497 type Target = T;
500 type Target = T;
498
501
499 fn deref(&self) -> &T {
502 fn deref(&self) -> &T {
500 self.data
503 self.data
501 }
504 }
502 }
505 }
503
506
504 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
507 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
505 fn deref_mut(&mut self) -> &mut T {
508 fn deref_mut(&mut self) -> &mut T {
506 self.data
509 self.data
507 }
510 }
508 }
511 }
509
512
510 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
513 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
511 ///
514 ///
512 /// TODO: this is a bit awkward to use, and a better (more complicated)
515 /// TODO: this is a bit awkward to use, and a better (more complicated)
513 /// procedural macro would simplify the interface a lot.
516 /// procedural macro would simplify the interface a lot.
514 ///
517 ///
515 /// # Parameters
518 /// # Parameters
516 ///
519 ///
517 /// * `$name` is the identifier to give to the resulting Rust struct.
520 /// * `$name` is the identifier to give to the resulting Rust struct.
518 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
521 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
519 /// * `$iterator_type` is the type of the Rust iterator.
522 /// * `$iterator_type` is the type of the Rust iterator.
520 /// * `$success_func` is a function for processing the Rust `(key, value)`
523 /// * `$success_func` is a function for processing the Rust `(key, value)`
521 /// tuple on iteration success, turning it into something Python understands.
524 /// tuple on iteration success, turning it into something Python understands.
522 /// * `$success_func` is the return type of `$success_func`
525 /// * `$success_func` is the return type of `$success_func`
523 ///
526 ///
524 /// # Example
527 /// # Example
525 ///
528 ///
526 /// ```
529 /// ```
527 /// struct MyStruct {
530 /// struct MyStruct {
528 /// inner: HashMap<Vec<u8>, Vec<u8>>;
531 /// inner: HashMap<Vec<u8>, Vec<u8>>;
529 /// }
532 /// }
530 ///
533 ///
531 /// py_class!(pub class MyType |py| {
534 /// py_class!(pub class MyType |py| {
532 /// data inner: PySharedRefCell<MyStruct>;
535 /// data inner: PySharedRefCell<MyStruct>;
533 ///
536 ///
534 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
537 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
535 /// let leaked_ref = self.inner_shared(py).leak_immutable()?;
538 /// let leaked_ref = self.inner_shared(py).leak_immutable()?;
536 /// MyTypeItemsIterator::from_inner(
539 /// MyTypeItemsIterator::from_inner(
537 /// py,
540 /// py,
538 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
541 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
539 /// )
542 /// )
540 /// }
543 /// }
541 /// });
544 /// });
542 ///
545 ///
543 /// impl MyType {
546 /// impl MyType {
544 /// fn translate_key_value(
547 /// fn translate_key_value(
545 /// py: Python,
548 /// py: Python,
546 /// res: (&Vec<u8>, &Vec<u8>),
549 /// res: (&Vec<u8>, &Vec<u8>),
547 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
550 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
548 /// let (f, entry) = res;
551 /// let (f, entry) = res;
549 /// Ok(Some((
552 /// Ok(Some((
550 /// PyBytes::new(py, f),
553 /// PyBytes::new(py, f),
551 /// PyBytes::new(py, entry),
554 /// PyBytes::new(py, entry),
552 /// )))
555 /// )))
553 /// }
556 /// }
554 /// }
557 /// }
555 ///
558 ///
556 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
559 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
557 ///
560 ///
558 /// py_shared_iterator!(
561 /// py_shared_iterator!(
559 /// MyTypeItemsIterator,
562 /// MyTypeItemsIterator,
560 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
563 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
561 /// MyType::translate_key_value,
564 /// MyType::translate_key_value,
562 /// Option<(PyBytes, PyBytes)>
565 /// Option<(PyBytes, PyBytes)>
563 /// );
566 /// );
564 /// ```
567 /// ```
565 macro_rules! py_shared_iterator {
568 macro_rules! py_shared_iterator {
566 (
569 (
567 $name: ident,
570 $name: ident,
568 $leaked: ty,
571 $leaked: ty,
569 $success_func: expr,
572 $success_func: expr,
570 $success_type: ty
573 $success_type: ty
571 ) => {
574 ) => {
572 py_class!(pub class $name |py| {
575 py_class!(pub class $name |py| {
573 data inner: RefCell<$leaked>;
576 data inner: RefCell<$leaked>;
574
577
575 def __next__(&self) -> PyResult<$success_type> {
578 def __next__(&self) -> PyResult<$success_type> {
576 let mut leaked = self.inner(py).borrow_mut();
579 let mut leaked = self.inner(py).borrow_mut();
577 let mut iter = leaked.try_borrow_mut(py)?;
580 let mut iter = leaked.try_borrow_mut(py)?;
578 match iter.next() {
581 match iter.next() {
579 None => Ok(None),
582 None => Ok(None),
580 Some(res) => $success_func(py, res),
583 Some(res) => $success_func(py, res),
581 }
584 }
582 }
585 }
583
586
584 def __iter__(&self) -> PyResult<Self> {
587 def __iter__(&self) -> PyResult<Self> {
585 Ok(self.clone_ref(py))
588 Ok(self.clone_ref(py))
586 }
589 }
587 });
590 });
588
591
589 impl $name {
592 impl $name {
590 pub fn from_inner(
593 pub fn from_inner(
591 py: Python,
594 py: Python,
592 leaked: $leaked,
595 leaked: $leaked,
593 ) -> PyResult<Self> {
596 ) -> PyResult<Self> {
594 Self::create_instance(
597 Self::create_instance(
595 py,
598 py,
596 RefCell::new(leaked),
599 RefCell::new(leaked),
597 )
600 )
598 }
601 }
599 }
602 }
600 };
603 };
601 }
604 }
602
605
603 #[cfg(test)]
606 #[cfg(test)]
604 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
607 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
605 mod test {
608 mod test {
606 use super::*;
609 use super::*;
607 use cpython::{GILGuard, Python};
610 use cpython::{GILGuard, Python};
608
611
609 py_class!(class Owner |py| {
612 py_class!(class Owner |py| {
610 data string: PySharedRefCell<String>;
613 data string: PySharedRefCell<String>;
611 });
614 });
612 py_shared_ref!(Owner, String, string, string_shared);
615 py_shared_ref!(Owner, String, string, string_shared);
613
616
614 fn prepare_env() -> (GILGuard, Owner) {
617 fn prepare_env() -> (GILGuard, Owner) {
615 let gil = Python::acquire_gil();
618 let gil = Python::acquire_gil();
616 let py = gil.python();
619 let py = gil.python();
617 let owner =
620 let owner =
618 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
621 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
619 .unwrap();
622 .unwrap();
620 (gil, owner)
623 (gil, owner)
621 }
624 }
622
625
623 #[test]
626 #[test]
624 fn test_leaked_borrow() {
627 fn test_leaked_borrow() {
625 let (gil, owner) = prepare_env();
628 let (gil, owner) = prepare_env();
626 let py = gil.python();
629 let py = gil.python();
627 let leaked = owner.string_shared(py).leak_immutable().unwrap();
630 let leaked = owner.string_shared(py).leak_immutable().unwrap();
628 let leaked_ref = leaked.try_borrow(py).unwrap();
631 let leaked_ref = leaked.try_borrow(py).unwrap();
629 assert_eq!(*leaked_ref, "new");
632 assert_eq!(*leaked_ref, "new");
630 }
633 }
631
634
632 #[test]
635 #[test]
633 fn test_leaked_borrow_mut() {
636 fn test_leaked_borrow_mut() {
634 let (gil, owner) = prepare_env();
637 let (gil, owner) = prepare_env();
635 let py = gil.python();
638 let py = gil.python();
636 let leaked = owner.string_shared(py).leak_immutable().unwrap();
639 let leaked = owner.string_shared(py).leak_immutable().unwrap();
637 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
640 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
638 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
641 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
639 assert_eq!(leaked_ref.next(), Some('n'));
642 assert_eq!(leaked_ref.next(), Some('n'));
640 assert_eq!(leaked_ref.next(), Some('e'));
643 assert_eq!(leaked_ref.next(), Some('e'));
641 assert_eq!(leaked_ref.next(), Some('w'));
644 assert_eq!(leaked_ref.next(), Some('w'));
642 assert_eq!(leaked_ref.next(), None);
645 assert_eq!(leaked_ref.next(), None);
643 }
646 }
644
647
645 #[test]
648 #[test]
646 fn test_leaked_borrow_after_mut() {
649 fn test_leaked_borrow_after_mut() {
647 let (gil, owner) = prepare_env();
650 let (gil, owner) = prepare_env();
648 let py = gil.python();
651 let py = gil.python();
649 let leaked = owner.string_shared(py).leak_immutable().unwrap();
652 let leaked = owner.string_shared(py).leak_immutable().unwrap();
650 owner.string_shared(py).borrow_mut().unwrap().clear();
653 owner.string_shared(py).borrow_mut().unwrap().clear();
651 assert!(leaked.try_borrow(py).is_err());
654 assert!(leaked.try_borrow(py).is_err());
652 }
655 }
653
656
654 #[test]
657 #[test]
655 fn test_leaked_borrow_mut_after_mut() {
658 fn test_leaked_borrow_mut_after_mut() {
656 let (gil, owner) = prepare_env();
659 let (gil, owner) = prepare_env();
657 let py = gil.python();
660 let py = gil.python();
658 let leaked = owner.string_shared(py).leak_immutable().unwrap();
661 let leaked = owner.string_shared(py).leak_immutable().unwrap();
659 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
662 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
660 owner.string_shared(py).borrow_mut().unwrap().clear();
663 owner.string_shared(py).borrow_mut().unwrap().clear();
661 assert!(leaked_iter.try_borrow_mut(py).is_err());
664 assert!(leaked_iter.try_borrow_mut(py).is_err());
662 }
665 }
663
666
664 #[test]
667 #[test]
665 #[should_panic(expected = "map() over invalidated leaked reference")]
668 #[should_panic(expected = "map() over invalidated leaked reference")]
666 fn test_leaked_map_after_mut() {
669 fn test_leaked_map_after_mut() {
667 let (gil, owner) = prepare_env();
670 let (gil, owner) = prepare_env();
668 let py = gil.python();
671 let py = gil.python();
669 let leaked = owner.string_shared(py).leak_immutable().unwrap();
672 let leaked = owner.string_shared(py).leak_immutable().unwrap();
670 owner.string_shared(py).borrow_mut().unwrap().clear();
673 owner.string_shared(py).borrow_mut().unwrap().clear();
671 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
674 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
672 }
675 }
673
676
674 #[test]
677 #[test]
675 fn test_borrow_mut_while_leaked_ref() {
678 fn test_borrow_mut_while_leaked_ref() {
676 let (gil, owner) = prepare_env();
679 let (gil, owner) = prepare_env();
677 let py = gil.python();
680 let py = gil.python();
678 assert!(owner.string_shared(py).borrow_mut().is_ok());
681 assert!(owner.string_shared(py).borrow_mut().is_ok());
679 let leaked = owner.string_shared(py).leak_immutable().unwrap();
682 let leaked = owner.string_shared(py).leak_immutable().unwrap();
680 {
683 {
681 let _leaked_ref = leaked.try_borrow(py).unwrap();
684 let _leaked_ref = leaked.try_borrow(py).unwrap();
682 assert!(owner.string_shared(py).borrow_mut().is_err());
685 assert!(owner.string_shared(py).borrow_mut().is_err());
683 {
686 {
684 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
687 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
685 assert!(owner.string_shared(py).borrow_mut().is_err());
688 assert!(owner.string_shared(py).borrow_mut().is_err());
686 }
689 }
687 assert!(owner.string_shared(py).borrow_mut().is_err());
690 assert!(owner.string_shared(py).borrow_mut().is_err());
688 }
691 }
689 assert!(owner.string_shared(py).borrow_mut().is_ok());
692 assert!(owner.string_shared(py).borrow_mut().is_ok());
690 }
693 }
691
694
692 #[test]
695 #[test]
693 fn test_borrow_mut_while_leaked_ref_mut() {
696 fn test_borrow_mut_while_leaked_ref_mut() {
694 let (gil, owner) = prepare_env();
697 let (gil, owner) = prepare_env();
695 let py = gil.python();
698 let py = gil.python();
696 assert!(owner.string_shared(py).borrow_mut().is_ok());
699 assert!(owner.string_shared(py).borrow_mut().is_ok());
697 let leaked = owner.string_shared(py).leak_immutable().unwrap();
700 let leaked = owner.string_shared(py).leak_immutable().unwrap();
698 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
701 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
699 {
702 {
700 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
703 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
701 assert!(owner.string_shared(py).borrow_mut().is_err());
704 assert!(owner.string_shared(py).borrow_mut().is_err());
702 }
705 }
703 assert!(owner.string_shared(py).borrow_mut().is_ok());
706 assert!(owner.string_shared(py).borrow_mut().is_ok());
704 }
707 }
708
709 #[test]
710 #[should_panic(expected = "mutably borrowed")]
711 fn test_leak_while_borrow_mut() {
712 let (gil, owner) = prepare_env();
713 let py = gil.python();
714 let _mut_ref = owner.string_shared(py).borrow_mut();
715 let _ = owner.string_shared(py).leak_immutable();
716 }
705 }
717 }
General Comments 0
You need to be logged in to leave comments. Login now