##// END OF EJS Templates
rust-cpython: inline PySharedState::leak_immutable() and PyLeaked::new()...
Yuya Nishihara -
r44687:f015d679 default
parent child Browse files
Show More
@@ -1,663 +1,634 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::{Ref, RefCell, RefMut};
27 use std::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
41 /// - The underlying `RefCell`, which prevents `PySharedRefCell` data from
42 /// being directly borrowed or leaked while it is mutably borrowed.
42 /// being directly borrowed or leaked while it is mutably borrowed.
43 /// - The `borrow_count`, which is the number of references borrowed from
43 /// - The `borrow_count`, which is the number of references borrowed from
44 /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked`
44 /// `PyLeaked`. Just like `RefCell`, mutation is prohibited while `PyLeaked`
45 /// is borrowed.
45 /// is borrowed.
46 /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked`
46 /// - The `generation` counter, which increments on `borrow_mut()`. `PyLeaked`
47 /// reference is valid only if the `current_generation()` equals to the
47 /// reference is valid only if the `current_generation()` equals to the
48 /// `generation` at the time of `leak_immutable()`.
48 /// `generation` at the time of `leak_immutable()`.
49 #[derive(Debug, Default)]
49 #[derive(Debug, Default)]
50 struct PySharedState {
50 struct PySharedState {
51 // The counter variable could be Cell<usize> since any operation on
51 // The counter variable could be Cell<usize> since any operation on
52 // PySharedState is synchronized by the GIL, but being "atomic" makes
52 // PySharedState is synchronized by the GIL, but being "atomic" makes
53 // PySharedState inherently Sync. The ordering requirement doesn't
53 // PySharedState inherently Sync. The ordering requirement doesn't
54 // matter thanks to the GIL.
54 // matter thanks to the GIL.
55 borrow_count: AtomicUsize,
55 borrow_count: AtomicUsize,
56 generation: AtomicUsize,
56 generation: AtomicUsize,
57 }
57 }
58
58
59 impl PySharedState {
59 impl PySharedState {
60 /// Return a reference to the wrapped data and its state with an
61 /// artificial static lifetime.
62 /// We need to be protected by the GIL for thread-safety.
63 ///
64 /// # Safety
65 ///
66 /// This is highly unsafe since the lifetime of the given data can be
67 /// extended. Do not call this function directly.
68 unsafe fn leak_immutable<T>(
69 &self,
70 _py: Python,
71 data: Ref<T>,
72 ) -> (&'static T, &'static PySharedState) {
73 let ptr: *const T = &*data;
74 let state_ptr: *const PySharedState = self;
75 (&*ptr, &*state_ptr)
76 }
77
78 fn current_borrow_count(&self, _py: Python) -> usize {
60 fn current_borrow_count(&self, _py: Python) -> usize {
79 self.borrow_count.load(Ordering::Relaxed)
61 self.borrow_count.load(Ordering::Relaxed)
80 }
62 }
81
63
82 fn increase_borrow_count(&self, _py: Python) {
64 fn increase_borrow_count(&self, _py: Python) {
83 // Note that this wraps around if there are more than usize::MAX
65 // Note that this wraps around if there are more than usize::MAX
84 // borrowed references, which shouldn't happen due to memory limit.
66 // borrowed references, which shouldn't happen due to memory limit.
85 self.borrow_count.fetch_add(1, Ordering::Relaxed);
67 self.borrow_count.fetch_add(1, Ordering::Relaxed);
86 }
68 }
87
69
88 fn decrease_borrow_count(&self, _py: Python) {
70 fn decrease_borrow_count(&self, _py: Python) {
89 let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed);
71 let prev_count = self.borrow_count.fetch_sub(1, Ordering::Relaxed);
90 assert!(prev_count > 0);
72 assert!(prev_count > 0);
91 }
73 }
92
74
93 fn current_generation(&self, _py: Python) -> usize {
75 fn current_generation(&self, _py: Python) -> usize {
94 self.generation.load(Ordering::Relaxed)
76 self.generation.load(Ordering::Relaxed)
95 }
77 }
96
78
97 fn increment_generation(&self, py: Python) {
79 fn increment_generation(&self, py: Python) {
98 assert_eq!(self.current_borrow_count(py), 0);
80 assert_eq!(self.current_borrow_count(py), 0);
99 // Note that this wraps around to the same value if mutably
81 // Note that this wraps around to the same value if mutably
100 // borrowed more than usize::MAX times, which wouldn't happen
82 // borrowed more than usize::MAX times, which wouldn't happen
101 // in practice.
83 // in practice.
102 self.generation.fetch_add(1, Ordering::Relaxed);
84 self.generation.fetch_add(1, Ordering::Relaxed);
103 }
85 }
104 }
86 }
105
87
106 /// Helper to keep the borrow count updated while the shared object is
88 /// Helper to keep the borrow count updated while the shared object is
107 /// immutably borrowed without using the `RefCell` interface.
89 /// immutably borrowed without using the `RefCell` interface.
108 struct BorrowPyShared<'a> {
90 struct BorrowPyShared<'a> {
109 py: Python<'a>,
91 py: Python<'a>,
110 py_shared_state: &'a PySharedState,
92 py_shared_state: &'a PySharedState,
111 }
93 }
112
94
113 impl<'a> BorrowPyShared<'a> {
95 impl<'a> BorrowPyShared<'a> {
114 fn new(
96 fn new(
115 py: Python<'a>,
97 py: Python<'a>,
116 py_shared_state: &'a PySharedState,
98 py_shared_state: &'a PySharedState,
117 ) -> BorrowPyShared<'a> {
99 ) -> BorrowPyShared<'a> {
118 py_shared_state.increase_borrow_count(py);
100 py_shared_state.increase_borrow_count(py);
119 BorrowPyShared {
101 BorrowPyShared {
120 py,
102 py,
121 py_shared_state,
103 py_shared_state,
122 }
104 }
123 }
105 }
124 }
106 }
125
107
126 impl Drop for BorrowPyShared<'_> {
108 impl Drop for BorrowPyShared<'_> {
127 fn drop(&mut self) {
109 fn drop(&mut self) {
128 self.py_shared_state.decrease_borrow_count(self.py);
110 self.py_shared_state.decrease_borrow_count(self.py);
129 }
111 }
130 }
112 }
131
113
132 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
114 /// `RefCell` wrapper to be safely used in conjunction with `PySharedState`.
133 ///
115 ///
134 /// This object can be stored in a `py_class!` object as a data field. Any
116 /// This object can be stored in a `py_class!` object as a data field. Any
135 /// operation is allowed through the `PySharedRef` interface.
117 /// operation is allowed through the `PySharedRef` interface.
136 #[derive(Debug)]
118 #[derive(Debug)]
137 pub struct PySharedRefCell<T> {
119 pub struct PySharedRefCell<T> {
138 inner: RefCell<T>,
120 inner: RefCell<T>,
139 py_shared_state: PySharedState,
121 py_shared_state: PySharedState,
140 }
122 }
141
123
142 impl<T> PySharedRefCell<T> {
124 impl<T> PySharedRefCell<T> {
143 pub fn new(value: T) -> PySharedRefCell<T> {
125 pub fn new(value: T) -> PySharedRefCell<T> {
144 Self {
126 Self {
145 inner: RefCell::new(value),
127 inner: RefCell::new(value),
146 py_shared_state: PySharedState::default(),
128 py_shared_state: PySharedState::default(),
147 }
129 }
148 }
130 }
149
131
150 fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> {
132 fn borrow<'a>(&'a self, _py: Python<'a>) -> Ref<'a, T> {
151 // py_shared_state isn't involved since
133 // py_shared_state isn't involved since
152 // - inner.borrow() would fail if self is mutably borrowed,
134 // - inner.borrow() would fail if self is mutably borrowed,
153 // - and inner.try_borrow_mut() would fail while self is borrowed.
135 // - and inner.try_borrow_mut() would fail while self is borrowed.
154 self.inner.borrow()
136 self.inner.borrow()
155 }
137 }
156
138
157 fn try_borrow_mut<'a>(
139 fn try_borrow_mut<'a>(
158 &'a self,
140 &'a self,
159 py: Python<'a>,
141 py: Python<'a>,
160 ) -> PyResult<RefMut<'a, T>> {
142 ) -> PyResult<RefMut<'a, T>> {
161 if self.py_shared_state.current_borrow_count(py) > 0 {
143 if self.py_shared_state.current_borrow_count(py) > 0 {
162 return Err(AlreadyBorrowed::new(
144 return Err(AlreadyBorrowed::new(
163 py,
145 py,
164 "Cannot borrow mutably while immutably borrowed",
146 "Cannot borrow mutably while immutably borrowed",
165 ));
147 ));
166 }
148 }
167 let inner_ref = self
149 let inner_ref = self
168 .inner
150 .inner
169 .try_borrow_mut()
151 .try_borrow_mut()
170 .map_err(|e| AlreadyBorrowed::new(py, e.to_string()))?;
152 .map_err(|e| AlreadyBorrowed::new(py, e.to_string()))?;
171 self.py_shared_state.increment_generation(py);
153 self.py_shared_state.increment_generation(py);
172 Ok(inner_ref)
154 Ok(inner_ref)
173 }
155 }
174 }
156 }
175
157
176 /// Sharable data member of type `T` borrowed from the `PyObject`.
158 /// Sharable data member of type `T` borrowed from the `PyObject`.
177 pub struct PySharedRef<'a, T> {
159 pub struct PySharedRef<'a, T> {
178 py: Python<'a>,
160 py: Python<'a>,
179 owner: &'a PyObject,
161 owner: &'a PyObject,
180 data: &'a PySharedRefCell<T>,
162 data: &'a PySharedRefCell<T>,
181 }
163 }
182
164
183 impl<'a, T> PySharedRef<'a, T> {
165 impl<'a, T> PySharedRef<'a, T> {
184 /// # Safety
166 /// # Safety
185 ///
167 ///
186 /// The `data` must be owned by the `owner`. Otherwise, the leak count
168 /// The `data` must be owned by the `owner`. Otherwise, the leak count
187 /// would get wrong.
169 /// would get wrong.
188 pub unsafe fn new(
170 pub unsafe fn new(
189 py: Python<'a>,
171 py: Python<'a>,
190 owner: &'a PyObject,
172 owner: &'a PyObject,
191 data: &'a PySharedRefCell<T>,
173 data: &'a PySharedRefCell<T>,
192 ) -> Self {
174 ) -> Self {
193 Self { py, owner, data }
175 Self { py, owner, data }
194 }
176 }
195
177
196 pub fn borrow(&self) -> Ref<'a, T> {
178 pub fn borrow(&self) -> Ref<'a, T> {
197 self.data.borrow(self.py)
179 self.data.borrow(self.py)
198 }
180 }
199
181
200 /// Mutably borrows the wrapped value.
182 /// Mutably borrows the wrapped value.
201 ///
183 ///
202 /// # Panics
184 /// # Panics
203 ///
185 ///
204 /// Panics if the value is currently borrowed through `PySharedRef`
186 /// Panics if the value is currently borrowed through `PySharedRef`
205 /// or `PyLeaked`.
187 /// or `PyLeaked`.
206 pub fn borrow_mut(&self) -> RefMut<'a, T> {
188 pub fn borrow_mut(&self) -> RefMut<'a, T> {
207 self.try_borrow_mut().expect("already borrowed")
189 self.try_borrow_mut().expect("already borrowed")
208 }
190 }
209
191
210 /// Mutably borrows the wrapped value, returning an error if the value
192 /// Mutably borrows the wrapped value, returning an error if the value
211 /// is currently borrowed.
193 /// is currently borrowed.
212 pub fn try_borrow_mut(&self) -> PyResult<RefMut<'a, T>> {
194 pub fn try_borrow_mut(&self) -> PyResult<RefMut<'a, T>> {
213 self.data.try_borrow_mut(self.py)
195 self.data.try_borrow_mut(self.py)
214 }
196 }
215
197
216 /// Returns a leaked reference.
198 /// Returns a leaked reference.
217 ///
199 ///
218 /// # Panics
200 /// # Panics
219 ///
201 ///
220 /// Panics if this is mutably borrowed.
202 /// Panics if this is mutably borrowed.
221 pub fn leak_immutable(&self) -> PyLeaked<&'static T> {
203 pub fn leak_immutable(&self) -> PyLeaked<&'static T> {
222 let state = &self.data.py_shared_state;
204 let state = &self.data.py_shared_state;
223 // make sure self.data isn't mutably borrowed; otherwise the
205 // make sure self.data isn't mutably borrowed; otherwise the
224 // generation number can't be trusted.
206 // generation number can't be trusted.
225 let data_ref = self.borrow();
207 let data_ref = self.borrow();
226 unsafe {
208
227 let (static_ref, static_state_ref) =
209 // &'static cast is safe because data_ptr and state_ptr are owned
228 state.leak_immutable(self.py, data_ref);
210 // by self.owner, and we do have the GIL for thread safety.
229 PyLeaked::new(self.py, self.owner, static_ref, static_state_ref)
211 let data_ptr: *const T = &*data_ref;
212 let state_ptr: *const PySharedState = state;
213 PyLeaked::<&'static T> {
214 inner: self.owner.clone_ref(self.py),
215 data: unsafe { &*data_ptr },
216 py_shared_state: unsafe { &*state_ptr },
217 generation: state.current_generation(self.py),
230 }
218 }
231 }
219 }
232 }
220 }
233
221
234 /// Allows a `py_class!` generated struct to share references to one of its
222 /// Allows a `py_class!` generated struct to share references to one of its
235 /// data members with Python.
223 /// data members with Python.
236 ///
224 ///
237 /// # Parameters
225 /// # Parameters
238 ///
226 ///
239 /// * `$name` is the same identifier used in for `py_class!` macro call.
227 /// * `$name` is the same identifier used in for `py_class!` macro call.
240 /// * `$inner_struct` is the identifier of the underlying Rust struct
228 /// * `$inner_struct` is the identifier of the underlying Rust struct
241 /// * `$data_member` is the identifier of the data member of `$inner_struct`
229 /// * `$data_member` is the identifier of the data member of `$inner_struct`
242 /// that will be shared.
230 /// that will be shared.
243 /// * `$shared_accessor` is the function name to be generated, which allows
231 /// * `$shared_accessor` is the function name to be generated, which allows
244 /// safe access to the data member.
232 /// safe access to the data member.
245 ///
233 ///
246 /// # Safety
234 /// # Safety
247 ///
235 ///
248 /// `$data_member` must persist while the `$name` object is alive. In other
236 /// `$data_member` must persist while the `$name` object is alive. In other
249 /// words, it must be an accessor to a data field of the Python object.
237 /// words, it must be an accessor to a data field of the Python object.
250 ///
238 ///
251 /// # Example
239 /// # Example
252 ///
240 ///
253 /// ```
241 /// ```
254 /// struct MyStruct {
242 /// struct MyStruct {
255 /// inner: Vec<u32>;
243 /// inner: Vec<u32>;
256 /// }
244 /// }
257 ///
245 ///
258 /// py_class!(pub class MyType |py| {
246 /// py_class!(pub class MyType |py| {
259 /// data inner: PySharedRefCell<MyStruct>;
247 /// data inner: PySharedRefCell<MyStruct>;
260 /// });
248 /// });
261 ///
249 ///
262 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
250 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
263 /// ```
251 /// ```
264 macro_rules! py_shared_ref {
252 macro_rules! py_shared_ref {
265 (
253 (
266 $name: ident,
254 $name: ident,
267 $inner_struct: ident,
255 $inner_struct: ident,
268 $data_member: ident,
256 $data_member: ident,
269 $shared_accessor: ident
257 $shared_accessor: ident
270 ) => {
258 ) => {
271 impl $name {
259 impl $name {
272 /// Returns a safe reference to the shared `$data_member`.
260 /// Returns a safe reference to the shared `$data_member`.
273 ///
261 ///
274 /// This function guarantees that `PySharedRef` is created with
262 /// This function guarantees that `PySharedRef` is created with
275 /// the valid `self` and `self.$data_member(py)` pair.
263 /// the valid `self` and `self.$data_member(py)` pair.
276 fn $shared_accessor<'a>(
264 fn $shared_accessor<'a>(
277 &'a self,
265 &'a self,
278 py: Python<'a>,
266 py: Python<'a>,
279 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
267 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
280 use cpython::PythonObject;
268 use cpython::PythonObject;
281 use $crate::ref_sharing::PySharedRef;
269 use $crate::ref_sharing::PySharedRef;
282 let owner = self.as_object();
270 let owner = self.as_object();
283 let data = self.$data_member(py);
271 let data = self.$data_member(py);
284 unsafe { PySharedRef::new(py, owner, data) }
272 unsafe { PySharedRef::new(py, owner, data) }
285 }
273 }
286 }
274 }
287 };
275 };
288 }
276 }
289
277
290 /// Manage immutable references to `PyObject` leaked into Python iterators.
278 /// Manage immutable references to `PyObject` leaked into Python iterators.
291 ///
279 ///
292 /// This reference will be invalidated once the original value is mutably
280 /// This reference will be invalidated once the original value is mutably
293 /// borrowed.
281 /// borrowed.
294 pub struct PyLeaked<T> {
282 pub struct PyLeaked<T> {
295 inner: PyObject,
283 inner: PyObject,
296 data: T,
284 data: T,
297 py_shared_state: &'static PySharedState,
285 py_shared_state: &'static PySharedState,
298 /// Generation counter of data `T` captured when PyLeaked is created.
286 /// Generation counter of data `T` captured when PyLeaked is created.
299 generation: usize,
287 generation: usize,
300 }
288 }
301
289
302 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
290 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
303 // without taking Python GIL wouldn't be safe. Also, the underling reference
291 // without taking Python GIL wouldn't be safe. Also, the underling reference
304 // is invalid if generation != py_shared_state.generation.
292 // is invalid if generation != py_shared_state.generation.
305
293
306 impl<T> PyLeaked<T> {
294 impl<T> PyLeaked<T> {
307 /// # Safety
308 ///
309 /// The `py_shared_state` must be owned by the `inner` Python object.
310 fn new(
311 py: Python,
312 inner: &PyObject,
313 data: T,
314 py_shared_state: &'static PySharedState,
315 ) -> Self {
316 Self {
317 inner: inner.clone_ref(py),
318 data: data,
319 py_shared_state,
320 generation: py_shared_state.current_generation(py),
321 }
322 }
323
324 /// Immutably borrows the wrapped value.
295 /// Immutably borrows the wrapped value.
325 ///
296 ///
326 /// Borrowing fails if the underlying reference has been invalidated.
297 /// Borrowing fails if the underlying reference has been invalidated.
327 pub fn try_borrow<'a>(
298 pub fn try_borrow<'a>(
328 &'a self,
299 &'a self,
329 py: Python<'a>,
300 py: Python<'a>,
330 ) -> PyResult<PyLeakedRef<'a, T>> {
301 ) -> PyResult<PyLeakedRef<'a, T>> {
331 self.validate_generation(py)?;
302 self.validate_generation(py)?;
332 Ok(PyLeakedRef {
303 Ok(PyLeakedRef {
333 _borrow: BorrowPyShared::new(py, self.py_shared_state),
304 _borrow: BorrowPyShared::new(py, self.py_shared_state),
334 data: &self.data,
305 data: &self.data,
335 })
306 })
336 }
307 }
337
308
338 /// Mutably borrows the wrapped value.
309 /// Mutably borrows the wrapped value.
339 ///
310 ///
340 /// Borrowing fails if the underlying reference has been invalidated.
311 /// Borrowing fails if the underlying reference has been invalidated.
341 ///
312 ///
342 /// Typically `T` is an iterator. If `T` is an immutable reference,
313 /// Typically `T` is an iterator. If `T` is an immutable reference,
343 /// `get_mut()` is useless since the inner value can't be mutated.
314 /// `get_mut()` is useless since the inner value can't be mutated.
344 pub fn try_borrow_mut<'a>(
315 pub fn try_borrow_mut<'a>(
345 &'a mut self,
316 &'a mut self,
346 py: Python<'a>,
317 py: Python<'a>,
347 ) -> PyResult<PyLeakedRefMut<'a, T>> {
318 ) -> PyResult<PyLeakedRefMut<'a, T>> {
348 self.validate_generation(py)?;
319 self.validate_generation(py)?;
349 Ok(PyLeakedRefMut {
320 Ok(PyLeakedRefMut {
350 _borrow: BorrowPyShared::new(py, self.py_shared_state),
321 _borrow: BorrowPyShared::new(py, self.py_shared_state),
351 data: &mut self.data,
322 data: &mut self.data,
352 })
323 })
353 }
324 }
354
325
355 /// Converts the inner value by the given function.
326 /// Converts the inner value by the given function.
356 ///
327 ///
357 /// Typically `T` is a static reference to a container, and `U` is an
328 /// Typically `T` is a static reference to a container, and `U` is an
358 /// iterator of that container.
329 /// iterator of that container.
359 ///
330 ///
360 /// # Panics
331 /// # Panics
361 ///
332 ///
362 /// Panics if the underlying reference has been invalidated.
333 /// Panics if the underlying reference has been invalidated.
363 ///
334 ///
364 /// This is typically called immediately after the `PyLeaked` is obtained.
335 /// This is typically called immediately after the `PyLeaked` is obtained.
365 /// In which case, the reference must be valid and no panic would occur.
336 /// In which case, the reference must be valid and no panic would occur.
366 ///
337 ///
367 /// # Safety
338 /// # Safety
368 ///
339 ///
369 /// The lifetime of the object passed in to the function `f` is cheated.
340 /// The lifetime of the object passed in to the function `f` is cheated.
370 /// It's typically a static reference, but is valid only while the
341 /// It's typically a static reference, but is valid only while the
371 /// corresponding `PyLeaked` is alive. Do not copy it out of the
342 /// corresponding `PyLeaked` is alive. Do not copy it out of the
372 /// function call.
343 /// function call.
373 pub unsafe fn map<U>(
344 pub unsafe fn map<U>(
374 self,
345 self,
375 py: Python,
346 py: Python,
376 f: impl FnOnce(T) -> U,
347 f: impl FnOnce(T) -> U,
377 ) -> PyLeaked<U> {
348 ) -> PyLeaked<U> {
378 // Needs to test the generation value to make sure self.data reference
349 // Needs to test the generation value to make sure self.data reference
379 // is still intact.
350 // is still intact.
380 self.validate_generation(py)
351 self.validate_generation(py)
381 .expect("map() over invalidated leaked reference");
352 .expect("map() over invalidated leaked reference");
382
353
383 // f() could make the self.data outlive. That's why map() is unsafe.
354 // f() could make the self.data outlive. That's why map() is unsafe.
384 // In order to make this function safe, maybe we'll need a way to
355 // In order to make this function safe, maybe we'll need a way to
385 // temporarily restrict the lifetime of self.data and translate the
356 // temporarily restrict the lifetime of self.data and translate the
386 // returned object back to Something<'static>.
357 // returned object back to Something<'static>.
387 let new_data = f(self.data);
358 let new_data = f(self.data);
388 PyLeaked {
359 PyLeaked {
389 inner: self.inner,
360 inner: self.inner,
390 data: new_data,
361 data: new_data,
391 py_shared_state: self.py_shared_state,
362 py_shared_state: self.py_shared_state,
392 generation: self.generation,
363 generation: self.generation,
393 }
364 }
394 }
365 }
395
366
396 fn validate_generation(&self, py: Python) -> PyResult<()> {
367 fn validate_generation(&self, py: Python) -> PyResult<()> {
397 if self.py_shared_state.current_generation(py) == self.generation {
368 if self.py_shared_state.current_generation(py) == self.generation {
398 Ok(())
369 Ok(())
399 } else {
370 } else {
400 Err(PyErr::new::<exc::RuntimeError, _>(
371 Err(PyErr::new::<exc::RuntimeError, _>(
401 py,
372 py,
402 "Cannot access to leaked reference after mutation",
373 "Cannot access to leaked reference after mutation",
403 ))
374 ))
404 }
375 }
405 }
376 }
406 }
377 }
407
378
408 /// Immutably borrowed reference to a leaked value.
379 /// Immutably borrowed reference to a leaked value.
409 pub struct PyLeakedRef<'a, T> {
380 pub struct PyLeakedRef<'a, T> {
410 _borrow: BorrowPyShared<'a>,
381 _borrow: BorrowPyShared<'a>,
411 data: &'a T,
382 data: &'a T,
412 }
383 }
413
384
414 impl<T> Deref for PyLeakedRef<'_, T> {
385 impl<T> Deref for PyLeakedRef<'_, T> {
415 type Target = T;
386 type Target = T;
416
387
417 fn deref(&self) -> &T {
388 fn deref(&self) -> &T {
418 self.data
389 self.data
419 }
390 }
420 }
391 }
421
392
422 /// Mutably borrowed reference to a leaked value.
393 /// Mutably borrowed reference to a leaked value.
423 pub struct PyLeakedRefMut<'a, T> {
394 pub struct PyLeakedRefMut<'a, T> {
424 _borrow: BorrowPyShared<'a>,
395 _borrow: BorrowPyShared<'a>,
425 data: &'a mut T,
396 data: &'a mut T,
426 }
397 }
427
398
428 impl<T> Deref for PyLeakedRefMut<'_, T> {
399 impl<T> Deref for PyLeakedRefMut<'_, T> {
429 type Target = T;
400 type Target = T;
430
401
431 fn deref(&self) -> &T {
402 fn deref(&self) -> &T {
432 self.data
403 self.data
433 }
404 }
434 }
405 }
435
406
436 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
407 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
437 fn deref_mut(&mut self) -> &mut T {
408 fn deref_mut(&mut self) -> &mut T {
438 self.data
409 self.data
439 }
410 }
440 }
411 }
441
412
442 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
413 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
443 ///
414 ///
444 /// TODO: this is a bit awkward to use, and a better (more complicated)
415 /// TODO: this is a bit awkward to use, and a better (more complicated)
445 /// procedural macro would simplify the interface a lot.
416 /// procedural macro would simplify the interface a lot.
446 ///
417 ///
447 /// # Parameters
418 /// # Parameters
448 ///
419 ///
449 /// * `$name` is the identifier to give to the resulting Rust struct.
420 /// * `$name` is the identifier to give to the resulting Rust struct.
450 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
421 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
451 /// * `$iterator_type` is the type of the Rust iterator.
422 /// * `$iterator_type` is the type of the Rust iterator.
452 /// * `$success_func` is a function for processing the Rust `(key, value)`
423 /// * `$success_func` is a function for processing the Rust `(key, value)`
453 /// tuple on iteration success, turning it into something Python understands.
424 /// tuple on iteration success, turning it into something Python understands.
454 /// * `$success_func` is the return type of `$success_func`
425 /// * `$success_func` is the return type of `$success_func`
455 ///
426 ///
456 /// # Example
427 /// # Example
457 ///
428 ///
458 /// ```
429 /// ```
459 /// struct MyStruct {
430 /// struct MyStruct {
460 /// inner: HashMap<Vec<u8>, Vec<u8>>;
431 /// inner: HashMap<Vec<u8>, Vec<u8>>;
461 /// }
432 /// }
462 ///
433 ///
463 /// py_class!(pub class MyType |py| {
434 /// py_class!(pub class MyType |py| {
464 /// data inner: PySharedRefCell<MyStruct>;
435 /// data inner: PySharedRefCell<MyStruct>;
465 ///
436 ///
466 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
437 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
467 /// let leaked_ref = self.inner_shared(py).leak_immutable();
438 /// let leaked_ref = self.inner_shared(py).leak_immutable();
468 /// MyTypeItemsIterator::from_inner(
439 /// MyTypeItemsIterator::from_inner(
469 /// py,
440 /// py,
470 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
441 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
471 /// )
442 /// )
472 /// }
443 /// }
473 /// });
444 /// });
474 ///
445 ///
475 /// impl MyType {
446 /// impl MyType {
476 /// fn translate_key_value(
447 /// fn translate_key_value(
477 /// py: Python,
448 /// py: Python,
478 /// res: (&Vec<u8>, &Vec<u8>),
449 /// res: (&Vec<u8>, &Vec<u8>),
479 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
450 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
480 /// let (f, entry) = res;
451 /// let (f, entry) = res;
481 /// Ok(Some((
452 /// Ok(Some((
482 /// PyBytes::new(py, f),
453 /// PyBytes::new(py, f),
483 /// PyBytes::new(py, entry),
454 /// PyBytes::new(py, entry),
484 /// )))
455 /// )))
485 /// }
456 /// }
486 /// }
457 /// }
487 ///
458 ///
488 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
459 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
489 ///
460 ///
490 /// py_shared_iterator!(
461 /// py_shared_iterator!(
491 /// MyTypeItemsIterator,
462 /// MyTypeItemsIterator,
492 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
463 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
493 /// MyType::translate_key_value,
464 /// MyType::translate_key_value,
494 /// Option<(PyBytes, PyBytes)>
465 /// Option<(PyBytes, PyBytes)>
495 /// );
466 /// );
496 /// ```
467 /// ```
497 macro_rules! py_shared_iterator {
468 macro_rules! py_shared_iterator {
498 (
469 (
499 $name: ident,
470 $name: ident,
500 $leaked: ty,
471 $leaked: ty,
501 $success_func: expr,
472 $success_func: expr,
502 $success_type: ty
473 $success_type: ty
503 ) => {
474 ) => {
504 py_class!(pub class $name |py| {
475 py_class!(pub class $name |py| {
505 data inner: RefCell<$leaked>;
476 data inner: RefCell<$leaked>;
506
477
507 def __next__(&self) -> PyResult<$success_type> {
478 def __next__(&self) -> PyResult<$success_type> {
508 let mut leaked = self.inner(py).borrow_mut();
479 let mut leaked = self.inner(py).borrow_mut();
509 let mut iter = leaked.try_borrow_mut(py)?;
480 let mut iter = leaked.try_borrow_mut(py)?;
510 match iter.next() {
481 match iter.next() {
511 None => Ok(None),
482 None => Ok(None),
512 Some(res) => $success_func(py, res),
483 Some(res) => $success_func(py, res),
513 }
484 }
514 }
485 }
515
486
516 def __iter__(&self) -> PyResult<Self> {
487 def __iter__(&self) -> PyResult<Self> {
517 Ok(self.clone_ref(py))
488 Ok(self.clone_ref(py))
518 }
489 }
519 });
490 });
520
491
521 impl $name {
492 impl $name {
522 pub fn from_inner(
493 pub fn from_inner(
523 py: Python,
494 py: Python,
524 leaked: $leaked,
495 leaked: $leaked,
525 ) -> PyResult<Self> {
496 ) -> PyResult<Self> {
526 Self::create_instance(
497 Self::create_instance(
527 py,
498 py,
528 RefCell::new(leaked),
499 RefCell::new(leaked),
529 )
500 )
530 }
501 }
531 }
502 }
532 };
503 };
533 }
504 }
534
505
535 #[cfg(test)]
506 #[cfg(test)]
536 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
507 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
537 mod test {
508 mod test {
538 use super::*;
509 use super::*;
539 use cpython::{GILGuard, Python};
510 use cpython::{GILGuard, Python};
540
511
541 py_class!(class Owner |py| {
512 py_class!(class Owner |py| {
542 data string: PySharedRefCell<String>;
513 data string: PySharedRefCell<String>;
543 });
514 });
544 py_shared_ref!(Owner, String, string, string_shared);
515 py_shared_ref!(Owner, String, string, string_shared);
545
516
546 fn prepare_env() -> (GILGuard, Owner) {
517 fn prepare_env() -> (GILGuard, Owner) {
547 let gil = Python::acquire_gil();
518 let gil = Python::acquire_gil();
548 let py = gil.python();
519 let py = gil.python();
549 let owner =
520 let owner =
550 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
521 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
551 .unwrap();
522 .unwrap();
552 (gil, owner)
523 (gil, owner)
553 }
524 }
554
525
555 #[test]
526 #[test]
556 fn test_leaked_borrow() {
527 fn test_leaked_borrow() {
557 let (gil, owner) = prepare_env();
528 let (gil, owner) = prepare_env();
558 let py = gil.python();
529 let py = gil.python();
559 let leaked = owner.string_shared(py).leak_immutable();
530 let leaked = owner.string_shared(py).leak_immutable();
560 let leaked_ref = leaked.try_borrow(py).unwrap();
531 let leaked_ref = leaked.try_borrow(py).unwrap();
561 assert_eq!(*leaked_ref, "new");
532 assert_eq!(*leaked_ref, "new");
562 }
533 }
563
534
564 #[test]
535 #[test]
565 fn test_leaked_borrow_mut() {
536 fn test_leaked_borrow_mut() {
566 let (gil, owner) = prepare_env();
537 let (gil, owner) = prepare_env();
567 let py = gil.python();
538 let py = gil.python();
568 let leaked = owner.string_shared(py).leak_immutable();
539 let leaked = owner.string_shared(py).leak_immutable();
569 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
540 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
570 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
541 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
571 assert_eq!(leaked_ref.next(), Some('n'));
542 assert_eq!(leaked_ref.next(), Some('n'));
572 assert_eq!(leaked_ref.next(), Some('e'));
543 assert_eq!(leaked_ref.next(), Some('e'));
573 assert_eq!(leaked_ref.next(), Some('w'));
544 assert_eq!(leaked_ref.next(), Some('w'));
574 assert_eq!(leaked_ref.next(), None);
545 assert_eq!(leaked_ref.next(), None);
575 }
546 }
576
547
577 #[test]
548 #[test]
578 fn test_leaked_borrow_after_mut() {
549 fn test_leaked_borrow_after_mut() {
579 let (gil, owner) = prepare_env();
550 let (gil, owner) = prepare_env();
580 let py = gil.python();
551 let py = gil.python();
581 let leaked = owner.string_shared(py).leak_immutable();
552 let leaked = owner.string_shared(py).leak_immutable();
582 owner.string_shared(py).borrow_mut().clear();
553 owner.string_shared(py).borrow_mut().clear();
583 assert!(leaked.try_borrow(py).is_err());
554 assert!(leaked.try_borrow(py).is_err());
584 }
555 }
585
556
586 #[test]
557 #[test]
587 fn test_leaked_borrow_mut_after_mut() {
558 fn test_leaked_borrow_mut_after_mut() {
588 let (gil, owner) = prepare_env();
559 let (gil, owner) = prepare_env();
589 let py = gil.python();
560 let py = gil.python();
590 let leaked = owner.string_shared(py).leak_immutable();
561 let leaked = owner.string_shared(py).leak_immutable();
591 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
562 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
592 owner.string_shared(py).borrow_mut().clear();
563 owner.string_shared(py).borrow_mut().clear();
593 assert!(leaked_iter.try_borrow_mut(py).is_err());
564 assert!(leaked_iter.try_borrow_mut(py).is_err());
594 }
565 }
595
566
596 #[test]
567 #[test]
597 #[should_panic(expected = "map() over invalidated leaked reference")]
568 #[should_panic(expected = "map() over invalidated leaked reference")]
598 fn test_leaked_map_after_mut() {
569 fn test_leaked_map_after_mut() {
599 let (gil, owner) = prepare_env();
570 let (gil, owner) = prepare_env();
600 let py = gil.python();
571 let py = gil.python();
601 let leaked = owner.string_shared(py).leak_immutable();
572 let leaked = owner.string_shared(py).leak_immutable();
602 owner.string_shared(py).borrow_mut().clear();
573 owner.string_shared(py).borrow_mut().clear();
603 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
574 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
604 }
575 }
605
576
606 #[test]
577 #[test]
607 fn test_try_borrow_mut_while_leaked_ref() {
578 fn test_try_borrow_mut_while_leaked_ref() {
608 let (gil, owner) = prepare_env();
579 let (gil, owner) = prepare_env();
609 let py = gil.python();
580 let py = gil.python();
610 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
581 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
611 let leaked = owner.string_shared(py).leak_immutable();
582 let leaked = owner.string_shared(py).leak_immutable();
612 {
583 {
613 let _leaked_ref = leaked.try_borrow(py).unwrap();
584 let _leaked_ref = leaked.try_borrow(py).unwrap();
614 assert!(owner.string_shared(py).try_borrow_mut().is_err());
585 assert!(owner.string_shared(py).try_borrow_mut().is_err());
615 {
586 {
616 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
587 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
617 assert!(owner.string_shared(py).try_borrow_mut().is_err());
588 assert!(owner.string_shared(py).try_borrow_mut().is_err());
618 }
589 }
619 assert!(owner.string_shared(py).try_borrow_mut().is_err());
590 assert!(owner.string_shared(py).try_borrow_mut().is_err());
620 }
591 }
621 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
592 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
622 }
593 }
623
594
624 #[test]
595 #[test]
625 fn test_try_borrow_mut_while_leaked_ref_mut() {
596 fn test_try_borrow_mut_while_leaked_ref_mut() {
626 let (gil, owner) = prepare_env();
597 let (gil, owner) = prepare_env();
627 let py = gil.python();
598 let py = gil.python();
628 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
599 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
629 let leaked = owner.string_shared(py).leak_immutable();
600 let leaked = owner.string_shared(py).leak_immutable();
630 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
601 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
631 {
602 {
632 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
603 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
633 assert!(owner.string_shared(py).try_borrow_mut().is_err());
604 assert!(owner.string_shared(py).try_borrow_mut().is_err());
634 }
605 }
635 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
606 assert!(owner.string_shared(py).try_borrow_mut().is_ok());
636 }
607 }
637
608
638 #[test]
609 #[test]
639 #[should_panic(expected = "mutably borrowed")]
610 #[should_panic(expected = "mutably borrowed")]
640 fn test_leak_while_borrow_mut() {
611 fn test_leak_while_borrow_mut() {
641 let (gil, owner) = prepare_env();
612 let (gil, owner) = prepare_env();
642 let py = gil.python();
613 let py = gil.python();
643 let _mut_ref = owner.string_shared(py).borrow_mut();
614 let _mut_ref = owner.string_shared(py).borrow_mut();
644 owner.string_shared(py).leak_immutable();
615 owner.string_shared(py).leak_immutable();
645 }
616 }
646
617
647 #[test]
618 #[test]
648 fn test_try_borrow_mut_while_borrow() {
619 fn test_try_borrow_mut_while_borrow() {
649 let (gil, owner) = prepare_env();
620 let (gil, owner) = prepare_env();
650 let py = gil.python();
621 let py = gil.python();
651 let _ref = owner.string_shared(py).borrow();
622 let _ref = owner.string_shared(py).borrow();
652 assert!(owner.string_shared(py).try_borrow_mut().is_err());
623 assert!(owner.string_shared(py).try_borrow_mut().is_err());
653 }
624 }
654
625
655 #[test]
626 #[test]
656 #[should_panic(expected = "already borrowed")]
627 #[should_panic(expected = "already borrowed")]
657 fn test_borrow_mut_while_borrow() {
628 fn test_borrow_mut_while_borrow() {
658 let (gil, owner) = prepare_env();
629 let (gil, owner) = prepare_env();
659 let py = gil.python();
630 let py = gil.python();
660 let _ref = owner.string_shared(py).borrow();
631 let _ref = owner.string_shared(py).borrow();
661 owner.string_shared(py).borrow_mut();
632 owner.string_shared(py).borrow_mut();
662 }
633 }
663 }
634 }
General Comments 0
You need to be logged in to leave comments. Login now