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