cell/cell.rs
1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Modified work Copyright 2018-2019 Daniel Mueller (deso@posteo.net).
6//
7// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10// option. This file may not be copied, modified, or distributed
11// except according to those terms.
12
13use std::cell::Cell;
14use std::cell::UnsafeCell;
15use std::cmp::Ordering;
16use std::fmt;
17use std::fmt::Debug;
18use std::fmt::Display;
19use std::mem;
20use std::ops::Deref;
21use std::ops::DerefMut;
22
23
24/// A mutable memory location with dynamically checked borrow rules
25///
26/// See the [module-level documentation](index.html) for more.
27pub struct RefCell<T: ?Sized> {
28 borrow: Cell<BorrowFlag>,
29 value: UnsafeCell<T>,
30}
31
32/// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
33pub struct BorrowError {
34 _private: (),
35}
36
37impl Debug for BorrowError {
38 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 f.debug_struct("BorrowError").finish()
40 }
41}
42
43impl Display for BorrowError {
44 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45 Display::fmt("already mutably borrowed", f)
46 }
47}
48
49/// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
50pub struct BorrowMutError {
51 _private: (),
52}
53
54impl Debug for BorrowMutError {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 f.debug_struct("BorrowMutError").finish()
57 }
58}
59
60impl Display for BorrowMutError {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 Display::fmt("already borrowed", f)
63 }
64}
65
66// Positive values represent the number of `Ref` active. Negative values
67// represent the number of `RefMut` active. Multiple `RefMut`s can only be
68// active at a time if they refer to distinct, nonoverlapping components of a
69// `RefCell` (e.g., different ranges of a slice).
70//
71// `Ref` and `RefMut` are both two words in size, and so there will likely never
72// be enough `Ref`s or `RefMut`s in existence to overflow half of the `usize`
73// range. Thus, a `BorrowFlag` will probably never overflow or underflow.
74// However, this is not a guarantee, as a pathological program could repeatedly
75// create and then mem::forget `Ref`s or `RefMut`s. Thus, all code must
76// explicitly check for overflow and underflow in order to avoid unsafety, or at
77// least behave correctly in the event that overflow or underflow happens (e.g.,
78// see BorrowRef::new).
79type BorrowFlag = isize;
80const UNUSED: BorrowFlag = 0;
81
82#[inline(always)]
83fn is_writing(x: BorrowFlag) -> bool {
84 x < UNUSED
85}
86
87#[inline(always)]
88fn is_reading(x: BorrowFlag) -> bool {
89 x > UNUSED
90}
91
92impl<T> RefCell<T> {
93 /// Creates a new `RefCell` containing `value`.
94 ///
95 /// # Examples
96 ///
97 /// ```
98 /// use std::cell::RefCell;
99 ///
100 /// let c = RefCell::new(5);
101 /// ```
102 #[inline]
103 pub const fn new(value: T) -> RefCell<T> {
104 RefCell {
105 value: UnsafeCell::new(value),
106 borrow: Cell::new(UNUSED),
107 }
108 }
109
110 /// Consumes the `RefCell`, returning the wrapped value.
111 ///
112 /// # Examples
113 ///
114 /// ```
115 /// use std::cell::RefCell;
116 ///
117 /// let c = RefCell::new(5);
118 ///
119 /// let five = c.into_inner();
120 /// ```
121 #[inline]
122 pub fn into_inner(self) -> T {
123 // Since this function takes `self` (the `RefCell`) by value, the
124 // compiler statically verifies that it is not currently borrowed.
125 // Therefore the following assertion is just a `debug_assert!`.
126 debug_assert!(self.borrow.get() == UNUSED);
127 self.value.into_inner()
128 }
129
130 /// Replaces the wrapped value with a new one, returning the old value,
131 /// without deinitializing either one.
132 ///
133 /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
134 ///
135 /// # Panics
136 ///
137 /// Panics if the value is currently borrowed.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// use std::cell::RefCell;
143 /// let cell = RefCell::new(5);
144 /// let old_value = cell.replace(6);
145 /// assert_eq!(old_value, 5);
146 /// assert_eq!(cell, RefCell::new(6));
147 /// ```
148 #[inline]
149 pub fn replace(&self, t: T) -> T {
150 mem::replace(&mut *self.borrow_mut(), t)
151 }
152
153 /// Replaces the wrapped value with a new one computed from `f`, returning
154 /// the old value, without deinitializing either one.
155 ///
156 /// # Panics
157 ///
158 /// Panics if the value is currently borrowed.
159 ///
160 /// # Examples
161 ///
162 /// ```
163 /// use std::cell::RefCell;
164 /// let cell = RefCell::new(5);
165 /// let old_value = cell.replace_with(|&mut old| old + 1);
166 /// assert_eq!(old_value, 5);
167 /// assert_eq!(cell, RefCell::new(6));
168 /// ```
169 #[inline]
170 pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
171 let mut_borrow = &mut *self.borrow_mut();
172 let replacement = f(mut_borrow);
173 mem::replace(mut_borrow, replacement)
174 }
175
176 /// Swaps the wrapped value of `self` with the wrapped value of `other`,
177 /// without deinitializing either one.
178 ///
179 /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
180 ///
181 /// # Panics
182 ///
183 /// Panics if the value in either `RefCell` is currently borrowed.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use std::cell::RefCell;
189 /// let c = RefCell::new(5);
190 /// let d = RefCell::new(6);
191 /// c.swap(&d);
192 /// assert_eq!(c, RefCell::new(6));
193 /// assert_eq!(d, RefCell::new(5));
194 /// ```
195 #[inline]
196 pub fn swap(&self, other: &Self) {
197 mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
198 }
199}
200
201impl<T: ?Sized> RefCell<T> {
202 /// Immutably borrows the wrapped value.
203 ///
204 /// The borrow lasts until the returned `Ref` exits scope. Multiple
205 /// immutable borrows can be taken out at the same time.
206 ///
207 /// # Panics
208 ///
209 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
210 /// [`try_borrow`](#method.try_borrow).
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use std::cell::RefCell;
216 ///
217 /// let c = RefCell::new(5);
218 ///
219 /// let borrowed_five = c.borrow();
220 /// let borrowed_five2 = c.borrow();
221 /// ```
222 ///
223 /// An example of panic:
224 ///
225 /// ```
226 /// use std::cell::RefCell;
227 /// use std::thread;
228 ///
229 /// let result = thread::spawn(move || {
230 /// let c = RefCell::new(5);
231 /// let m = c.borrow_mut();
232 ///
233 /// let b = c.borrow(); // this causes a panic
234 /// }).join();
235 ///
236 /// assert!(result.is_err());
237 /// ```
238 #[inline]
239 pub fn borrow(&self) -> Ref<T> {
240 self.try_borrow().expect("already mutably borrowed")
241 }
242
243 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
244 /// borrowed.
245 ///
246 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
247 /// taken out at the same time.
248 ///
249 /// This is the non-panicking variant of [`borrow`](#method.borrow).
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use std::cell::RefCell;
255 ///
256 /// let c = RefCell::new(5);
257 ///
258 /// {
259 /// let m = c.borrow_mut();
260 /// assert!(c.try_borrow().is_err());
261 /// }
262 ///
263 /// {
264 /// let m = c.borrow();
265 /// assert!(c.try_borrow().is_ok());
266 /// }
267 /// ```
268 #[inline]
269 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
270 match BorrowRef::new(&self.borrow) {
271 Some(b) => Ok(Ref {
272 value: unsafe { &*self.value.get() },
273 borrow: b,
274 }),
275 None => Err(BorrowError { _private: () }),
276 }
277 }
278
279 /// Mutably borrows the wrapped value.
280 ///
281 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
282 /// from it exit scope. The value cannot be borrowed while this borrow is
283 /// active.
284 ///
285 /// # Panics
286 ///
287 /// Panics if the value is currently borrowed. For a non-panicking variant, use
288 /// [`try_borrow_mut`](#method.try_borrow_mut).
289 ///
290 /// # Examples
291 ///
292 /// ```
293 /// use std::cell::RefCell;
294 ///
295 /// let c = RefCell::new(5);
296 ///
297 /// *c.borrow_mut() = 7;
298 ///
299 /// assert_eq!(*c.borrow(), 7);
300 /// ```
301 ///
302 /// An example of panic:
303 ///
304 /// ```
305 /// use std::cell::RefCell;
306 /// use std::thread;
307 ///
308 /// let result = thread::spawn(move || {
309 /// let c = RefCell::new(5);
310 /// let m = c.borrow();
311 ///
312 /// let b = c.borrow_mut(); // this causes a panic
313 /// }).join();
314 ///
315 /// assert!(result.is_err());
316 /// ```
317 #[inline]
318 pub fn borrow_mut(&self) -> RefMut<T> {
319 self.try_borrow_mut().expect("already borrowed")
320 }
321
322 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
323 ///
324 /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived
325 /// from it exit scope. The value cannot be borrowed while this borrow is
326 /// active.
327 ///
328 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
329 ///
330 /// # Examples
331 ///
332 /// ```
333 /// use std::cell::RefCell;
334 ///
335 /// let c = RefCell::new(5);
336 ///
337 /// {
338 /// let m = c.borrow();
339 /// assert!(c.try_borrow_mut().is_err());
340 /// }
341 ///
342 /// assert!(c.try_borrow_mut().is_ok());
343 /// ```
344 #[inline]
345 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
346 match BorrowRefMut::new(&self.borrow) {
347 Some(b) => Ok(RefMut {
348 value: unsafe { &mut *self.value.get() },
349 borrow: b,
350 }),
351 None => Err(BorrowMutError { _private: () }),
352 }
353 }
354
355 /// Returns a raw pointer to the underlying data in this cell.
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// use std::cell::RefCell;
361 ///
362 /// let c = RefCell::new(5);
363 ///
364 /// let ptr = c.as_ptr();
365 /// ```
366 #[inline]
367 pub fn as_ptr(&self) -> *mut T {
368 self.value.get()
369 }
370
371 /// Returns a mutable reference to the underlying data.
372 ///
373 /// This call borrows `RefCell` mutably (at compile-time) so there is no
374 /// need for dynamic checks.
375 ///
376 /// However be cautious: this method expects `self` to be mutable, which is
377 /// generally not the case when using a `RefCell`. Take a look at the
378 /// [`borrow_mut`] method instead if `self` isn't mutable.
379 ///
380 /// Also, please be aware that this method is only for special circumstances and is usually
381 /// not what you want. In case of doubt, use [`borrow_mut`] instead.
382 ///
383 /// [`borrow_mut`]: #method.borrow_mut
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// use std::cell::RefCell;
389 ///
390 /// let mut c = RefCell::new(5);
391 /// *c.get_mut() += 1;
392 ///
393 /// assert_eq!(c, RefCell::new(6));
394 /// ```
395 #[inline]
396 pub fn get_mut(&mut self) -> &mut T {
397 unsafe {
398 &mut *self.value.get()
399 }
400 }
401}
402
403unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
404
405// Note that `RefCell` does not explicitly have a negative trait bound
406// for `Sync` as negative trait bounds are only available on nightly but
407// we want to be available on stable. However, `RefCell` still won't
408// implement `Sync` as it contains an `std::cell::UnsafeCell` which has
409// such a negative trait bound for `Sync`.
410
411impl<T: Clone> Clone for RefCell<T> {
412 /// # Panics
413 ///
414 /// Panics if the value is currently mutably borrowed.
415 #[inline]
416 fn clone(&self) -> RefCell<T> {
417 RefCell::new(self.borrow().clone())
418 }
419}
420
421impl<T:Default> Default for RefCell<T> {
422 /// Creates a `RefCell<T>`, with the `Default` value for T.
423 #[inline]
424 fn default() -> RefCell<T> {
425 RefCell::new(Default::default())
426 }
427}
428
429impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
430 /// # Panics
431 ///
432 /// Panics if the value in either `RefCell` is currently borrowed.
433 #[inline]
434 fn eq(&self, other: &RefCell<T>) -> bool {
435 *self.borrow() == *other.borrow()
436 }
437}
438
439impl<T: ?Sized + Eq> Eq for RefCell<T> {}
440
441impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
442 /// # Panics
443 ///
444 /// Panics if the value in either `RefCell` is currently borrowed.
445 #[inline]
446 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
447 self.borrow().partial_cmp(&*other.borrow())
448 }
449
450 /// # Panics
451 ///
452 /// Panics if the value in either `RefCell` is currently borrowed.
453 #[inline]
454 fn lt(&self, other: &RefCell<T>) -> bool {
455 *self.borrow() < *other.borrow()
456 }
457
458 /// # Panics
459 ///
460 /// Panics if the value in either `RefCell` is currently borrowed.
461 #[inline]
462 fn le(&self, other: &RefCell<T>) -> bool {
463 *self.borrow() <= *other.borrow()
464 }
465
466 /// # Panics
467 ///
468 /// Panics if the value in either `RefCell` is currently borrowed.
469 #[inline]
470 fn gt(&self, other: &RefCell<T>) -> bool {
471 *self.borrow() > *other.borrow()
472 }
473
474 /// # Panics
475 ///
476 /// Panics if the value in either `RefCell` is currently borrowed.
477 #[inline]
478 fn ge(&self, other: &RefCell<T>) -> bool {
479 *self.borrow() >= *other.borrow()
480 }
481}
482
483impl<T: ?Sized + Ord> Ord for RefCell<T> {
484 /// # Panics
485 ///
486 /// Panics if the value in either `RefCell` is currently borrowed.
487 #[inline]
488 fn cmp(&self, other: &RefCell<T>) -> Ordering {
489 self.borrow().cmp(&*other.borrow())
490 }
491}
492
493impl<T> From<T> for RefCell<T> {
494 fn from(t: T) -> RefCell<T> {
495 RefCell::new(t)
496 }
497}
498
499struct BorrowRef<'b> {
500 borrow: &'b Cell<BorrowFlag>,
501}
502
503impl<'b> BorrowRef<'b> {
504 #[inline]
505 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
506 let b = borrow.get();
507 if is_writing(b) || b == isize::max_value() {
508 // If there's currently a writing borrow, or if incrementing the
509 // refcount would overflow into a writing borrow.
510 None
511 } else {
512 borrow.set(b + 1);
513 Some(BorrowRef { borrow })
514 }
515 }
516}
517
518impl Drop for BorrowRef<'_> {
519 #[inline]
520 fn drop(&mut self) {
521 let borrow = self.borrow.get();
522 debug_assert!(is_reading(borrow));
523 self.borrow.set(borrow - 1);
524 }
525}
526
527impl Clone for BorrowRef<'_> {
528 #[inline]
529 fn clone(&self) -> Self {
530 // Since this Ref exists, we know the borrow flag
531 // is a reading borrow.
532 let borrow = self.borrow.get();
533 debug_assert!(is_reading(borrow));
534 // Prevent the borrow counter from overflowing into
535 // a writing borrow.
536 assert!(borrow != isize::max_value());
537 self.borrow.set(borrow + 1);
538 BorrowRef { borrow: self.borrow }
539 }
540}
541
542/// Wraps a borrowed reference to a value in a `RefCell` box.
543/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
544///
545/// See the [module-level documentation](index.html) for more.
546pub struct Ref<'b, T: ?Sized + 'b> {
547 value: &'b T,
548 borrow: BorrowRef<'b>,
549}
550
551impl<T: ?Sized> Deref for Ref<'_, T> {
552 type Target = T;
553
554 #[inline]
555 fn deref(&self) -> &T {
556 self.value
557 }
558}
559
560impl<'b, T: ?Sized> Ref<'b, T> {
561 /// Copies a `Ref`.
562 ///
563 /// The `RefCell` is already immutably borrowed, so this cannot fail.
564 ///
565 /// This is an associated function that needs to be used as
566 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
567 /// with the widespread use of `r.borrow().clone()` to clone the contents of
568 /// a `RefCell`.
569 #[inline]
570 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
571 Ref {
572 value: orig.value,
573 borrow: orig.borrow.clone(),
574 }
575 }
576
577 /// Makes a new `Ref` for a component of the borrowed data.
578 ///
579 /// The `RefCell` is already immutably borrowed, so this cannot fail.
580 ///
581 /// This is an associated function that needs to be used as `Ref::map(...)`.
582 /// A method would interfere with methods of the same name on the contents
583 /// of a `RefCell` used through `Deref`.
584 ///
585 /// # Examples
586 ///
587 /// ```
588 /// use std::cell::{RefCell, Ref};
589 ///
590 /// let c = RefCell::new((5, 'b'));
591 /// let b1: Ref<(u32, char)> = c.borrow();
592 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
593 /// assert_eq!(*b2, 5)
594 /// ```
595 #[inline]
596 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
597 where F: FnOnce(&T) -> &U
598 {
599 Ref {
600 value: f(orig.value),
601 borrow: orig.borrow,
602 }
603 }
604
605 /// Splits a `Ref` into multiple `Ref`s for different components of the
606 /// borrowed data.
607 ///
608 /// The `RefCell` is already immutably borrowed, so this cannot fail.
609 ///
610 /// This is an associated function that needs to be used as
611 /// `Ref::map_split(...)`. A method would interfere with methods of the same
612 /// name on the contents of a `RefCell` used through `Deref`.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// use std::cell::{Ref, RefCell};
618 ///
619 /// let cell = RefCell::new([1, 2, 3, 4]);
620 /// let borrow = cell.borrow();
621 /// let (begin, end) = Ref::map_split(borrow, |slice| slice.split_at(2));
622 /// assert_eq!(*begin, [1, 2]);
623 /// assert_eq!(*end, [3, 4]);
624 /// ```
625 #[inline]
626 pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>)
627 where F: FnOnce(&T) -> (&U, &V)
628 {
629 let (a, b) = f(orig.value);
630 let borrow = orig.borrow.clone();
631 (Ref { value: a, borrow }, Ref { value: b, borrow: orig.borrow })
632 }
633
634 /// Make a new `RefVal` from the borrowed data.
635 ///
636 /// The `RefCell` is already immutably borrowed, so this operation
637 /// cannot fail.
638 #[inline]
639 pub fn map_val<U: Sized, F>(orig: Ref<'b, T>, f: F) -> RefVal<'b, U>
640 where F: FnOnce(&'b T) -> U
641 {
642 RefVal {
643 value: f(orig.value),
644 borrow: orig.borrow,
645 }
646 }
647}
648
649impl<T: ?Sized + fmt::Display> fmt::Display for Ref<'_, T> {
650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651 self.value.fmt(f)
652 }
653}
654
655impl<'b, T: ?Sized> RefMut<'b, T> {
656 /// Makes a new `RefMut` for a component of the borrowed data, e.g., an enum
657 /// variant.
658 ///
659 /// The `RefCell` is already mutably borrowed, so this cannot fail.
660 ///
661 /// This is an associated function that needs to be used as
662 /// `RefMut::map(...)`. A method would interfere with methods of the same
663 /// name on the contents of a `RefCell` used through `Deref`.
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// use std::cell::{RefCell, RefMut};
669 ///
670 /// let c = RefCell::new((5, 'b'));
671 /// {
672 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
673 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
674 /// assert_eq!(*b2, 5);
675 /// *b2 = 42;
676 /// }
677 /// assert_eq!(*c.borrow(), (42, 'b'));
678 /// ```
679 #[inline]
680 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
681 where F: FnOnce(&mut T) -> &mut U
682 {
683 // FIXME(nll-rfc#40): fix borrow-check
684 let RefMut { value, borrow } = orig;
685 RefMut {
686 value: f(value),
687 borrow,
688 }
689 }
690
691 /// Splits a `RefMut` into multiple `RefMut`s for different components of the
692 /// borrowed data.
693 ///
694 /// The underlying `RefCell` will remain mutably borrowed until both
695 /// returned `RefMut`s go out of scope.
696 ///
697 /// The `RefCell` is already mutably borrowed, so this cannot fail.
698 ///
699 /// This is an associated function that needs to be used as
700 /// `RefMut::map_split(...)`. A method would interfere with methods of the
701 /// same name on the contents of a `RefCell` used through `Deref`.
702 ///
703 /// # Examples
704 ///
705 /// ```
706 /// use std::cell::{RefCell, RefMut};
707 ///
708 /// let cell = RefCell::new([1, 2, 3, 4]);
709 /// let borrow = cell.borrow_mut();
710 /// let (mut begin, mut end) = RefMut::map_split(borrow, |slice| slice.split_at_mut(2));
711 /// assert_eq!(*begin, [1, 2]);
712 /// assert_eq!(*end, [3, 4]);
713 /// begin.copy_from_slice(&[4, 3]);
714 /// end.copy_from_slice(&[2, 1]);
715 /// ```
716 #[inline]
717 pub fn map_split<U: ?Sized, V: ?Sized, F>(
718 orig: RefMut<'b, T>, f: F
719 ) -> (RefMut<'b, U>, RefMut<'b, V>)
720 where F: FnOnce(&mut T) -> (&mut U, &mut V)
721 {
722 let (a, b) = f(orig.value);
723 let borrow = orig.borrow.clone();
724 (RefMut { value: a, borrow }, RefMut { value: b, borrow: orig.borrow })
725 }
726
727 /// Make a new `RefValMut` from the borrowed data.
728 ///
729 /// The `RefCell` is already immutably borrowed, so this operation
730 /// cannot fail.
731 #[inline]
732 pub fn map_val<U: Sized, F>(orig: RefMut<'b, T>, f: F) -> RefValMut<'b, U>
733 where F: FnOnce(&'b mut T) -> U
734 {
735 RefValMut {
736 value: f(orig.value),
737 borrow: orig.borrow,
738 }
739 }
740}
741
742struct BorrowRefMut<'b> {
743 borrow: &'b Cell<BorrowFlag>,
744}
745
746impl Drop for BorrowRefMut<'_> {
747 #[inline]
748 fn drop(&mut self) {
749 let borrow = self.borrow.get();
750 debug_assert!(is_writing(borrow));
751 self.borrow.set(borrow + 1);
752 }
753}
754
755impl<'b> BorrowRefMut<'b> {
756 #[inline]
757 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
758 // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial
759 // mutable reference, and so there must currently be no existing
760 // references. Thus, while clone increments the mutable refcount, here
761 // we explicitly only allow going from UNUSED to UNUSED - 1.
762 match borrow.get() {
763 UNUSED => {
764 borrow.set(UNUSED - 1);
765 Some(BorrowRefMut { borrow })
766 },
767 _ => None,
768 }
769 }
770
771 // Clone a `BorrowRefMut`.
772 //
773 // This is only valid if each `BorrowRefMut` is used to track a mutable
774 // reference to a distinct, nonoverlapping range of the original object.
775 // This isn't in a Clone impl so that code doesn't call this implicitly.
776 #[inline]
777 fn clone(&self) -> BorrowRefMut<'b> {
778 let borrow = self.borrow.get();
779 debug_assert!(is_writing(borrow));
780 // Prevent the borrow counter from underflowing.
781 assert!(borrow != isize::min_value());
782 self.borrow.set(borrow - 1);
783 BorrowRefMut { borrow: self.borrow }
784 }
785}
786
787/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
788///
789/// See the [module-level documentation](index.html) for more.
790pub struct RefMut<'b, T: ?Sized + 'b> {
791 value: &'b mut T,
792 borrow: BorrowRefMut<'b>,
793}
794
795impl<T: ?Sized> Deref for RefMut<'_, T> {
796 type Target = T;
797
798 #[inline]
799 fn deref(&self) -> &T {
800 self.value
801 }
802}
803
804impl<T: ?Sized> DerefMut for RefMut<'_, T> {
805 #[inline]
806 fn deref_mut(&mut self) -> &mut T {
807 self.value
808 }
809}
810
811impl<T: ?Sized + fmt::Display> fmt::Display for RefMut<'_, T> {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 self.value.fmt(f)
814 }
815}
816
817
818/// A type containing a value that contains a borrowed reference to a
819/// value from a `RefCell<T>`.
820///
821/// See the [module-level documentation](index.html) for more.
822pub struct RefVal<'b, T> {
823 value: T,
824 borrow: BorrowRef<'b>,
825}
826
827impl<'b, T> RefVal<'b, T> {
828 /// Copies a `RefVal`.
829 ///
830 /// The `RefCell` is already immutably borrowed, so this cannot fail.
831 ///
832 /// This is an associated function that needs to be used as
833 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
834 /// with the widespread use of `r.borrow().clone()` to clone the contents of
835 /// a `RefCell`.
836 #[inline]
837 pub fn clone(orig: &RefVal<'b, T>) -> RefVal<'b, T>
838 where T: Clone
839 {
840 RefVal {
841 value: orig.value.clone(),
842 borrow: orig.borrow.clone(),
843 }
844 }
845
846 /// Make a new `RefVal` from the another `RefVal`.
847 ///
848 /// The `RefCell` is already immutably borrowed, so this operation
849 /// cannot fail.
850 #[inline]
851 pub fn map<U: Sized, F>(orig: RefVal<'b, T>, f: F) -> RefVal<'b, U>
852 where F: FnOnce(T) -> U
853 {
854 RefVal {
855 value: f(orig.value),
856 borrow: orig.borrow,
857 }
858 }
859}
860
861
862impl<T> Deref for RefVal<'_, T> {
863 type Target = T;
864
865 #[inline]
866 fn deref(&self) -> &T {
867 &self.value
868 }
869}
870
871impl<T> DerefMut for RefVal<'_, T> {
872 #[inline]
873 fn deref_mut(&mut self) -> &mut T {
874 &mut self.value
875 }
876}
877
878impl<T: fmt::Display> fmt::Display for RefVal<'_, T> {
879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
880 self.value.fmt(f)
881 }
882}
883
884
885/// A type containing a value that contains a borrowed mutable reference
886/// to a value from a `RefCell<T>`.
887///
888/// See the [module-level documentation](index.html) for more.
889pub struct RefValMut<'b, T> {
890 value: T,
891 borrow: BorrowRefMut<'b>,
892}
893
894impl<'b, T> RefValMut<'b, T> {
895 /// Make a new `RefValMut` from the another `RefValMut`.
896 ///
897 /// The `RefCell` is already mutably borrowed, so this operation
898 /// cannot fail.
899 #[inline]
900 pub fn map<U: Sized, F>(orig: RefValMut<'b, T>, f: F) -> RefValMut<'b, U>
901 where F: FnOnce(T) -> U
902 {
903 RefValMut {
904 value: f(orig.value),
905 borrow: orig.borrow,
906 }
907 }
908}
909
910impl<T> Deref for RefValMut<'_, T> {
911 type Target = T;
912
913 #[inline]
914 fn deref(&self) -> &T {
915 &self.value
916 }
917}
918
919impl<T> DerefMut for RefValMut<'_, T> {
920 #[inline]
921 fn deref_mut(&mut self) -> &mut T {
922 &mut self.value
923 }
924}
925
926impl<T: fmt::Display> fmt::Display for RefValMut<'_, T> {
927 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
928 self.value.fmt(f)
929 }
930}