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