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