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