##// END OF EJS Templates
rust-cpython: remove useless wrappers from PyLeaked, just move by map()...
Yuya Nishihara -
r44649:1f9e6fbd default
parent child Browse files
Show More
@@ -1,636 +1,636 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<RefMut<'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)
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 ) -> (&'static T, &'static PySharedState) {
92 ) -> (&'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 (&*ptr, &*state_ptr)
95 (&*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<RefMut<'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<RefMut<'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) -> PyLeaked<&'static T> {
211 pub fn leak_immutable(&self) -> 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 PyLeaked::new(self.py, self.owner, static_ref, static_state_ref)
219 PyLeaked::new(self.py, self.owner, static_ref, static_state_ref)
220 }
220 }
221 }
221 }
222 }
222 }
223
223
224 /// Allows a `py_class!` generated struct to share references to one of its
224 /// Allows a `py_class!` generated struct to share references to one of its
225 /// data members with Python.
225 /// data members with Python.
226 ///
226 ///
227 /// # Parameters
227 /// # Parameters
228 ///
228 ///
229 /// * `$name` is the same identifier used in for `py_class!` macro call.
229 /// * `$name` is the same identifier used in for `py_class!` macro call.
230 /// * `$inner_struct` is the identifier of the underlying Rust struct
230 /// * `$inner_struct` is the identifier of the underlying Rust struct
231 /// * `$data_member` is the identifier of the data member of `$inner_struct`
231 /// * `$data_member` is the identifier of the data member of `$inner_struct`
232 /// that will be shared.
232 /// that will be shared.
233 /// * `$shared_accessor` is the function name to be generated, which allows
233 /// * `$shared_accessor` is the function name to be generated, which allows
234 /// safe access to the data member.
234 /// safe access to the data member.
235 ///
235 ///
236 /// # Safety
236 /// # Safety
237 ///
237 ///
238 /// `$data_member` must persist while the `$name` object is alive. In other
238 /// `$data_member` must persist while the `$name` object is alive. In other
239 /// words, it must be an accessor to a data field of the Python object.
239 /// words, it must be an accessor to a data field of the Python object.
240 ///
240 ///
241 /// # Example
241 /// # Example
242 ///
242 ///
243 /// ```
243 /// ```
244 /// struct MyStruct {
244 /// struct MyStruct {
245 /// inner: Vec<u32>;
245 /// inner: Vec<u32>;
246 /// }
246 /// }
247 ///
247 ///
248 /// py_class!(pub class MyType |py| {
248 /// py_class!(pub class MyType |py| {
249 /// data inner: PySharedRefCell<MyStruct>;
249 /// data inner: PySharedRefCell<MyStruct>;
250 /// });
250 /// });
251 ///
251 ///
252 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
252 /// py_shared_ref!(MyType, MyStruct, inner, inner_shared);
253 /// ```
253 /// ```
254 macro_rules! py_shared_ref {
254 macro_rules! py_shared_ref {
255 (
255 (
256 $name: ident,
256 $name: ident,
257 $inner_struct: ident,
257 $inner_struct: ident,
258 $data_member: ident,
258 $data_member: ident,
259 $shared_accessor: ident
259 $shared_accessor: ident
260 ) => {
260 ) => {
261 impl $name {
261 impl $name {
262 /// Returns a safe reference to the shared `$data_member`.
262 /// Returns a safe reference to the shared `$data_member`.
263 ///
263 ///
264 /// This function guarantees that `PySharedRef` is created with
264 /// This function guarantees that `PySharedRef` is created with
265 /// the valid `self` and `self.$data_member(py)` pair.
265 /// the valid `self` and `self.$data_member(py)` pair.
266 fn $shared_accessor<'a>(
266 fn $shared_accessor<'a>(
267 &'a self,
267 &'a self,
268 py: Python<'a>,
268 py: Python<'a>,
269 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
269 ) -> $crate::ref_sharing::PySharedRef<'a, $inner_struct> {
270 use cpython::PythonObject;
270 use cpython::PythonObject;
271 use $crate::ref_sharing::PySharedRef;
271 use $crate::ref_sharing::PySharedRef;
272 let owner = self.as_object();
272 let owner = self.as_object();
273 let data = self.$data_member(py);
273 let data = self.$data_member(py);
274 unsafe { PySharedRef::new(py, owner, data) }
274 unsafe { PySharedRef::new(py, owner, data) }
275 }
275 }
276 }
276 }
277 };
277 };
278 }
278 }
279
279
280 /// Manage immutable references to `PyObject` leaked into Python iterators.
280 /// Manage immutable references to `PyObject` leaked into Python iterators.
281 ///
281 ///
282 /// This reference will be invalidated once the original value is mutably
282 /// This reference will be invalidated once the original value is mutably
283 /// borrowed.
283 /// borrowed.
284 pub struct PyLeaked<T> {
284 pub struct PyLeaked<T> {
285 inner: PyObject,
285 inner: PyObject,
286 data: Option<T>,
286 data: T,
287 py_shared_state: &'static PySharedState,
287 py_shared_state: &'static PySharedState,
288 /// Generation counter of data `T` captured when PyLeaked is created.
288 /// Generation counter of data `T` captured when PyLeaked is created.
289 generation: usize,
289 generation: usize,
290 }
290 }
291
291
292 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
292 // DO NOT implement Deref for PyLeaked<T>! Dereferencing PyLeaked
293 // without taking Python GIL wouldn't be safe. Also, the underling reference
293 // without taking Python GIL wouldn't be safe. Also, the underling reference
294 // is invalid if generation != py_shared_state.generation.
294 // is invalid if generation != py_shared_state.generation.
295
295
296 impl<T> PyLeaked<T> {
296 impl<T> PyLeaked<T> {
297 /// # Safety
297 /// # Safety
298 ///
298 ///
299 /// The `py_shared_state` must be owned by the `inner` Python object.
299 /// The `py_shared_state` must be owned by the `inner` Python object.
300 fn new(
300 fn new(
301 py: Python,
301 py: Python,
302 inner: &PyObject,
302 inner: &PyObject,
303 data: T,
303 data: T,
304 py_shared_state: &'static PySharedState,
304 py_shared_state: &'static PySharedState,
305 ) -> Self {
305 ) -> Self {
306 Self {
306 Self {
307 inner: inner.clone_ref(py),
307 inner: inner.clone_ref(py),
308 data: Some(data),
308 data: data,
309 py_shared_state,
309 py_shared_state,
310 generation: py_shared_state.current_generation(py),
310 generation: py_shared_state.current_generation(py),
311 }
311 }
312 }
312 }
313
313
314 /// Immutably borrows the wrapped value.
314 /// Immutably borrows the wrapped value.
315 ///
315 ///
316 /// Borrowing fails if the underlying reference has been invalidated.
316 /// Borrowing fails if the underlying reference has been invalidated.
317 pub fn try_borrow<'a>(
317 pub fn try_borrow<'a>(
318 &'a self,
318 &'a self,
319 py: Python<'a>,
319 py: Python<'a>,
320 ) -> PyResult<PyLeakedRef<'a, T>> {
320 ) -> PyResult<PyLeakedRef<'a, T>> {
321 self.validate_generation(py)?;
321 self.validate_generation(py)?;
322 Ok(PyLeakedRef {
322 Ok(PyLeakedRef {
323 _borrow: BorrowPyShared::new(py, self.py_shared_state),
323 _borrow: BorrowPyShared::new(py, self.py_shared_state),
324 data: self.data.as_ref().unwrap(),
324 data: &self.data,
325 })
325 })
326 }
326 }
327
327
328 /// Mutably borrows the wrapped value.
328 /// Mutably borrows the wrapped value.
329 ///
329 ///
330 /// Borrowing fails if the underlying reference has been invalidated.
330 /// Borrowing fails if the underlying reference has been invalidated.
331 ///
331 ///
332 /// Typically `T` is an iterator. If `T` is an immutable reference,
332 /// Typically `T` is an iterator. If `T` is an immutable reference,
333 /// `get_mut()` is useless since the inner value can't be mutated.
333 /// `get_mut()` is useless since the inner value can't be mutated.
334 pub fn try_borrow_mut<'a>(
334 pub fn try_borrow_mut<'a>(
335 &'a mut self,
335 &'a mut self,
336 py: Python<'a>,
336 py: Python<'a>,
337 ) -> PyResult<PyLeakedRefMut<'a, T>> {
337 ) -> PyResult<PyLeakedRefMut<'a, T>> {
338 self.validate_generation(py)?;
338 self.validate_generation(py)?;
339 Ok(PyLeakedRefMut {
339 Ok(PyLeakedRefMut {
340 _borrow: BorrowPyShared::new(py, self.py_shared_state),
340 _borrow: BorrowPyShared::new(py, self.py_shared_state),
341 data: self.data.as_mut().unwrap(),
341 data: &mut self.data,
342 })
342 })
343 }
343 }
344
344
345 /// Converts the inner value by the given function.
345 /// Converts the inner value by the given function.
346 ///
346 ///
347 /// Typically `T` is a static reference to a container, and `U` is an
347 /// Typically `T` is a static reference to a container, and `U` is an
348 /// iterator of that container.
348 /// iterator of that container.
349 ///
349 ///
350 /// # Panics
350 /// # Panics
351 ///
351 ///
352 /// Panics if the underlying reference has been invalidated.
352 /// Panics if the underlying reference has been invalidated.
353 ///
353 ///
354 /// This is typically called immediately after the `PyLeaked` is obtained.
354 /// This is typically called immediately after the `PyLeaked` is obtained.
355 /// In which case, the reference must be valid and no panic would occur.
355 /// In which case, the reference must be valid and no panic would occur.
356 ///
356 ///
357 /// # Safety
357 /// # Safety
358 ///
358 ///
359 /// The lifetime of the object passed in to the function `f` is cheated.
359 /// The lifetime of the object passed in to the function `f` is cheated.
360 /// It's typically a static reference, but is valid only while the
360 /// It's typically a static reference, but is valid only while the
361 /// corresponding `PyLeaked` is alive. Do not copy it out of the
361 /// corresponding `PyLeaked` is alive. Do not copy it out of the
362 /// function call.
362 /// function call.
363 pub unsafe fn map<U>(
363 pub unsafe fn map<U>(
364 mut self,
364 self,
365 py: Python,
365 py: Python,
366 f: impl FnOnce(T) -> U,
366 f: impl FnOnce(T) -> U,
367 ) -> PyLeaked<U> {
367 ) -> PyLeaked<U> {
368 // Needs to test the generation value to make sure self.data reference
368 // Needs to test the generation value to make sure self.data reference
369 // is still intact.
369 // is still intact.
370 self.validate_generation(py)
370 self.validate_generation(py)
371 .expect("map() over invalidated leaked reference");
371 .expect("map() over invalidated leaked reference");
372
372
373 // f() could make the self.data outlive. That's why map() is unsafe.
373 // f() could make the self.data outlive. That's why map() is unsafe.
374 // In order to make this function safe, maybe we'll need a way to
374 // In order to make this function safe, maybe we'll need a way to
375 // temporarily restrict the lifetime of self.data and translate the
375 // temporarily restrict the lifetime of self.data and translate the
376 // returned object back to Something<'static>.
376 // returned object back to Something<'static>.
377 let new_data = f(self.data.take().unwrap());
377 let new_data = f(self.data);
378 PyLeaked {
378 PyLeaked {
379 inner: self.inner.clone_ref(py),
379 inner: self.inner,
380 data: Some(new_data),
380 data: new_data,
381 py_shared_state: self.py_shared_state,
381 py_shared_state: self.py_shared_state,
382 generation: self.generation,
382 generation: self.generation,
383 }
383 }
384 }
384 }
385
385
386 fn validate_generation(&self, py: Python) -> PyResult<()> {
386 fn validate_generation(&self, py: Python) -> PyResult<()> {
387 if self.py_shared_state.current_generation(py) == self.generation {
387 if self.py_shared_state.current_generation(py) == self.generation {
388 Ok(())
388 Ok(())
389 } else {
389 } else {
390 Err(PyErr::new::<exc::RuntimeError, _>(
390 Err(PyErr::new::<exc::RuntimeError, _>(
391 py,
391 py,
392 "Cannot access to leaked reference after mutation",
392 "Cannot access to leaked reference after mutation",
393 ))
393 ))
394 }
394 }
395 }
395 }
396 }
396 }
397
397
398 /// Immutably borrowed reference to a leaked value.
398 /// Immutably borrowed reference to a leaked value.
399 pub struct PyLeakedRef<'a, T> {
399 pub struct PyLeakedRef<'a, T> {
400 _borrow: BorrowPyShared<'a>,
400 _borrow: BorrowPyShared<'a>,
401 data: &'a T,
401 data: &'a T,
402 }
402 }
403
403
404 impl<T> Deref for PyLeakedRef<'_, T> {
404 impl<T> Deref for PyLeakedRef<'_, T> {
405 type Target = T;
405 type Target = T;
406
406
407 fn deref(&self) -> &T {
407 fn deref(&self) -> &T {
408 self.data
408 self.data
409 }
409 }
410 }
410 }
411
411
412 /// Mutably borrowed reference to a leaked value.
412 /// Mutably borrowed reference to a leaked value.
413 pub struct PyLeakedRefMut<'a, T> {
413 pub struct PyLeakedRefMut<'a, T> {
414 _borrow: BorrowPyShared<'a>,
414 _borrow: BorrowPyShared<'a>,
415 data: &'a mut T,
415 data: &'a mut T,
416 }
416 }
417
417
418 impl<T> Deref for PyLeakedRefMut<'_, T> {
418 impl<T> Deref for PyLeakedRefMut<'_, T> {
419 type Target = T;
419 type Target = T;
420
420
421 fn deref(&self) -> &T {
421 fn deref(&self) -> &T {
422 self.data
422 self.data
423 }
423 }
424 }
424 }
425
425
426 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
426 impl<T> DerefMut for PyLeakedRefMut<'_, T> {
427 fn deref_mut(&mut self) -> &mut T {
427 fn deref_mut(&mut self) -> &mut T {
428 self.data
428 self.data
429 }
429 }
430 }
430 }
431
431
432 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
432 /// Defines a `py_class!` that acts as a Python iterator over a Rust iterator.
433 ///
433 ///
434 /// TODO: this is a bit awkward to use, and a better (more complicated)
434 /// TODO: this is a bit awkward to use, and a better (more complicated)
435 /// procedural macro would simplify the interface a lot.
435 /// procedural macro would simplify the interface a lot.
436 ///
436 ///
437 /// # Parameters
437 /// # Parameters
438 ///
438 ///
439 /// * `$name` is the identifier to give to the resulting Rust struct.
439 /// * `$name` is the identifier to give to the resulting Rust struct.
440 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
440 /// * `$leaked` corresponds to `$leaked` in the matching `py_shared_ref!` call.
441 /// * `$iterator_type` is the type of the Rust iterator.
441 /// * `$iterator_type` is the type of the Rust iterator.
442 /// * `$success_func` is a function for processing the Rust `(key, value)`
442 /// * `$success_func` is a function for processing the Rust `(key, value)`
443 /// tuple on iteration success, turning it into something Python understands.
443 /// tuple on iteration success, turning it into something Python understands.
444 /// * `$success_func` is the return type of `$success_func`
444 /// * `$success_func` is the return type of `$success_func`
445 ///
445 ///
446 /// # Example
446 /// # Example
447 ///
447 ///
448 /// ```
448 /// ```
449 /// struct MyStruct {
449 /// struct MyStruct {
450 /// inner: HashMap<Vec<u8>, Vec<u8>>;
450 /// inner: HashMap<Vec<u8>, Vec<u8>>;
451 /// }
451 /// }
452 ///
452 ///
453 /// py_class!(pub class MyType |py| {
453 /// py_class!(pub class MyType |py| {
454 /// data inner: PySharedRefCell<MyStruct>;
454 /// data inner: PySharedRefCell<MyStruct>;
455 ///
455 ///
456 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
456 /// def __iter__(&self) -> PyResult<MyTypeItemsIterator> {
457 /// let leaked_ref = self.inner_shared(py).leak_immutable();
457 /// let leaked_ref = self.inner_shared(py).leak_immutable();
458 /// MyTypeItemsIterator::from_inner(
458 /// MyTypeItemsIterator::from_inner(
459 /// py,
459 /// py,
460 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
460 /// unsafe { leaked_ref.map(py, |o| o.iter()) },
461 /// )
461 /// )
462 /// }
462 /// }
463 /// });
463 /// });
464 ///
464 ///
465 /// impl MyType {
465 /// impl MyType {
466 /// fn translate_key_value(
466 /// fn translate_key_value(
467 /// py: Python,
467 /// py: Python,
468 /// res: (&Vec<u8>, &Vec<u8>),
468 /// res: (&Vec<u8>, &Vec<u8>),
469 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
469 /// ) -> PyResult<Option<(PyBytes, PyBytes)>> {
470 /// let (f, entry) = res;
470 /// let (f, entry) = res;
471 /// Ok(Some((
471 /// Ok(Some((
472 /// PyBytes::new(py, f),
472 /// PyBytes::new(py, f),
473 /// PyBytes::new(py, entry),
473 /// PyBytes::new(py, entry),
474 /// )))
474 /// )))
475 /// }
475 /// }
476 /// }
476 /// }
477 ///
477 ///
478 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
478 /// py_shared_ref!(MyType, MyStruct, inner, MyTypeLeakedRef);
479 ///
479 ///
480 /// py_shared_iterator!(
480 /// py_shared_iterator!(
481 /// MyTypeItemsIterator,
481 /// MyTypeItemsIterator,
482 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
482 /// PyLeaked<HashMap<'static, Vec<u8>, Vec<u8>>>,
483 /// MyType::translate_key_value,
483 /// MyType::translate_key_value,
484 /// Option<(PyBytes, PyBytes)>
484 /// Option<(PyBytes, PyBytes)>
485 /// );
485 /// );
486 /// ```
486 /// ```
487 macro_rules! py_shared_iterator {
487 macro_rules! py_shared_iterator {
488 (
488 (
489 $name: ident,
489 $name: ident,
490 $leaked: ty,
490 $leaked: ty,
491 $success_func: expr,
491 $success_func: expr,
492 $success_type: ty
492 $success_type: ty
493 ) => {
493 ) => {
494 py_class!(pub class $name |py| {
494 py_class!(pub class $name |py| {
495 data inner: RefCell<$leaked>;
495 data inner: RefCell<$leaked>;
496
496
497 def __next__(&self) -> PyResult<$success_type> {
497 def __next__(&self) -> PyResult<$success_type> {
498 let mut leaked = self.inner(py).borrow_mut();
498 let mut leaked = self.inner(py).borrow_mut();
499 let mut iter = leaked.try_borrow_mut(py)?;
499 let mut iter = leaked.try_borrow_mut(py)?;
500 match iter.next() {
500 match iter.next() {
501 None => Ok(None),
501 None => Ok(None),
502 Some(res) => $success_func(py, res),
502 Some(res) => $success_func(py, res),
503 }
503 }
504 }
504 }
505
505
506 def __iter__(&self) -> PyResult<Self> {
506 def __iter__(&self) -> PyResult<Self> {
507 Ok(self.clone_ref(py))
507 Ok(self.clone_ref(py))
508 }
508 }
509 });
509 });
510
510
511 impl $name {
511 impl $name {
512 pub fn from_inner(
512 pub fn from_inner(
513 py: Python,
513 py: Python,
514 leaked: $leaked,
514 leaked: $leaked,
515 ) -> PyResult<Self> {
515 ) -> PyResult<Self> {
516 Self::create_instance(
516 Self::create_instance(
517 py,
517 py,
518 RefCell::new(leaked),
518 RefCell::new(leaked),
519 )
519 )
520 }
520 }
521 }
521 }
522 };
522 };
523 }
523 }
524
524
525 #[cfg(test)]
525 #[cfg(test)]
526 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
526 #[cfg(any(feature = "python27-bin", feature = "python3-bin"))]
527 mod test {
527 mod test {
528 use super::*;
528 use super::*;
529 use cpython::{GILGuard, Python};
529 use cpython::{GILGuard, Python};
530
530
531 py_class!(class Owner |py| {
531 py_class!(class Owner |py| {
532 data string: PySharedRefCell<String>;
532 data string: PySharedRefCell<String>;
533 });
533 });
534 py_shared_ref!(Owner, String, string, string_shared);
534 py_shared_ref!(Owner, String, string, string_shared);
535
535
536 fn prepare_env() -> (GILGuard, Owner) {
536 fn prepare_env() -> (GILGuard, Owner) {
537 let gil = Python::acquire_gil();
537 let gil = Python::acquire_gil();
538 let py = gil.python();
538 let py = gil.python();
539 let owner =
539 let owner =
540 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
540 Owner::create_instance(py, PySharedRefCell::new("new".to_owned()))
541 .unwrap();
541 .unwrap();
542 (gil, owner)
542 (gil, owner)
543 }
543 }
544
544
545 #[test]
545 #[test]
546 fn test_leaked_borrow() {
546 fn test_leaked_borrow() {
547 let (gil, owner) = prepare_env();
547 let (gil, owner) = prepare_env();
548 let py = gil.python();
548 let py = gil.python();
549 let leaked = owner.string_shared(py).leak_immutable();
549 let leaked = owner.string_shared(py).leak_immutable();
550 let leaked_ref = leaked.try_borrow(py).unwrap();
550 let leaked_ref = leaked.try_borrow(py).unwrap();
551 assert_eq!(*leaked_ref, "new");
551 assert_eq!(*leaked_ref, "new");
552 }
552 }
553
553
554 #[test]
554 #[test]
555 fn test_leaked_borrow_mut() {
555 fn test_leaked_borrow_mut() {
556 let (gil, owner) = prepare_env();
556 let (gil, owner) = prepare_env();
557 let py = gil.python();
557 let py = gil.python();
558 let leaked = owner.string_shared(py).leak_immutable();
558 let leaked = owner.string_shared(py).leak_immutable();
559 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
559 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
560 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
560 let mut leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
561 assert_eq!(leaked_ref.next(), Some('n'));
561 assert_eq!(leaked_ref.next(), Some('n'));
562 assert_eq!(leaked_ref.next(), Some('e'));
562 assert_eq!(leaked_ref.next(), Some('e'));
563 assert_eq!(leaked_ref.next(), Some('w'));
563 assert_eq!(leaked_ref.next(), Some('w'));
564 assert_eq!(leaked_ref.next(), None);
564 assert_eq!(leaked_ref.next(), None);
565 }
565 }
566
566
567 #[test]
567 #[test]
568 fn test_leaked_borrow_after_mut() {
568 fn test_leaked_borrow_after_mut() {
569 let (gil, owner) = prepare_env();
569 let (gil, owner) = prepare_env();
570 let py = gil.python();
570 let py = gil.python();
571 let leaked = owner.string_shared(py).leak_immutable();
571 let leaked = owner.string_shared(py).leak_immutable();
572 owner.string_shared(py).borrow_mut().unwrap().clear();
572 owner.string_shared(py).borrow_mut().unwrap().clear();
573 assert!(leaked.try_borrow(py).is_err());
573 assert!(leaked.try_borrow(py).is_err());
574 }
574 }
575
575
576 #[test]
576 #[test]
577 fn test_leaked_borrow_mut_after_mut() {
577 fn test_leaked_borrow_mut_after_mut() {
578 let (gil, owner) = prepare_env();
578 let (gil, owner) = prepare_env();
579 let py = gil.python();
579 let py = gil.python();
580 let leaked = owner.string_shared(py).leak_immutable();
580 let leaked = owner.string_shared(py).leak_immutable();
581 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
581 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
582 owner.string_shared(py).borrow_mut().unwrap().clear();
582 owner.string_shared(py).borrow_mut().unwrap().clear();
583 assert!(leaked_iter.try_borrow_mut(py).is_err());
583 assert!(leaked_iter.try_borrow_mut(py).is_err());
584 }
584 }
585
585
586 #[test]
586 #[test]
587 #[should_panic(expected = "map() over invalidated leaked reference")]
587 #[should_panic(expected = "map() over invalidated leaked reference")]
588 fn test_leaked_map_after_mut() {
588 fn test_leaked_map_after_mut() {
589 let (gil, owner) = prepare_env();
589 let (gil, owner) = prepare_env();
590 let py = gil.python();
590 let py = gil.python();
591 let leaked = owner.string_shared(py).leak_immutable();
591 let leaked = owner.string_shared(py).leak_immutable();
592 owner.string_shared(py).borrow_mut().unwrap().clear();
592 owner.string_shared(py).borrow_mut().unwrap().clear();
593 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
593 let _leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
594 }
594 }
595
595
596 #[test]
596 #[test]
597 fn test_borrow_mut_while_leaked_ref() {
597 fn test_borrow_mut_while_leaked_ref() {
598 let (gil, owner) = prepare_env();
598 let (gil, owner) = prepare_env();
599 let py = gil.python();
599 let py = gil.python();
600 assert!(owner.string_shared(py).borrow_mut().is_ok());
600 assert!(owner.string_shared(py).borrow_mut().is_ok());
601 let leaked = owner.string_shared(py).leak_immutable();
601 let leaked = owner.string_shared(py).leak_immutable();
602 {
602 {
603 let _leaked_ref = leaked.try_borrow(py).unwrap();
603 let _leaked_ref = leaked.try_borrow(py).unwrap();
604 assert!(owner.string_shared(py).borrow_mut().is_err());
604 assert!(owner.string_shared(py).borrow_mut().is_err());
605 {
605 {
606 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
606 let _leaked_ref2 = leaked.try_borrow(py).unwrap();
607 assert!(owner.string_shared(py).borrow_mut().is_err());
607 assert!(owner.string_shared(py).borrow_mut().is_err());
608 }
608 }
609 assert!(owner.string_shared(py).borrow_mut().is_err());
609 assert!(owner.string_shared(py).borrow_mut().is_err());
610 }
610 }
611 assert!(owner.string_shared(py).borrow_mut().is_ok());
611 assert!(owner.string_shared(py).borrow_mut().is_ok());
612 }
612 }
613
613
614 #[test]
614 #[test]
615 fn test_borrow_mut_while_leaked_ref_mut() {
615 fn test_borrow_mut_while_leaked_ref_mut() {
616 let (gil, owner) = prepare_env();
616 let (gil, owner) = prepare_env();
617 let py = gil.python();
617 let py = gil.python();
618 assert!(owner.string_shared(py).borrow_mut().is_ok());
618 assert!(owner.string_shared(py).borrow_mut().is_ok());
619 let leaked = owner.string_shared(py).leak_immutable();
619 let leaked = owner.string_shared(py).leak_immutable();
620 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
620 let mut leaked_iter = unsafe { leaked.map(py, |s| s.chars()) };
621 {
621 {
622 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
622 let _leaked_ref = leaked_iter.try_borrow_mut(py).unwrap();
623 assert!(owner.string_shared(py).borrow_mut().is_err());
623 assert!(owner.string_shared(py).borrow_mut().is_err());
624 }
624 }
625 assert!(owner.string_shared(py).borrow_mut().is_ok());
625 assert!(owner.string_shared(py).borrow_mut().is_ok());
626 }
626 }
627
627
628 #[test]
628 #[test]
629 #[should_panic(expected = "mutably borrowed")]
629 #[should_panic(expected = "mutably borrowed")]
630 fn test_leak_while_borrow_mut() {
630 fn test_leak_while_borrow_mut() {
631 let (gil, owner) = prepare_env();
631 let (gil, owner) = prepare_env();
632 let py = gil.python();
632 let py = gil.python();
633 let _mut_ref = owner.string_shared(py).borrow_mut();
633 let _mut_ref = owner.string_shared(py).borrow_mut();
634 owner.string_shared(py).leak_immutable();
634 owner.string_shared(py).leak_immutable();
635 }
635 }
636 }
636 }
General Comments 0
You need to be logged in to leave comments. Login now