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