]> git.lizzy.rs Git - rust.git/blob - src/libcore/cell.rs
36618e86968b5ea3d0fecf4c684bed1b6b0f0ca2
[rust.git] / src / libcore / 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 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Shareable mutable containers.
12 //!
13 //! Rust memory safety is based on this rule: Given an object `T`, it is only possible to
14 //! have one of the following:
15 //!
16 //! - Having several immutable references (`&T`) to the object (also known as **aliasing**).
17 //! - Having one mutable reference (`&mut T`) to the object (also known as **mutability**).
18 //!
19 //! This is enforced by the Rust compiler. However, there are situations where this rule is not
20 //! flexible enough. Sometimes it is required to have multiple references to an object and yet
21 //! mutate it.
22 //!
23 //! Shareable mutable containers exist to permit mutability in a controlled manner, even in the
24 //! presence of aliasing. Both `Cell<T>` and `RefCell<T>` allows to do this in a single threaded
25 //! way. However, neither `Cell<T>` nor `RefCell<T>` are thread safe (they do not implement
26 //! `Sync`). If you need to do aliasing and mutation between multiple threads it is possible to
27 //! use [`Mutex`](../../std/sync/struct.Mutex.html),
28 //! [`RwLock`](../../std/sync/struct.RwLock.html) or
29 //! [`atomic`](../../core/sync/atomic/index.html) types.
30 //!
31 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
32 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
33 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
34 //! with typical Rust types that exhibit 'inherited mutability'.
35 //!
36 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` implements interior
37 //! mutability by moving values in and out of the `Cell<T>`. To use references instead of values,
38 //! one must use the `RefCell<T>` type, acquiring a write lock before mutating. `Cell<T>` provides
39 //! methods to retrieve and change the current interior value:
40 //!
41 //!  - For types that implement `Copy`, the `get` method retrieves the current interior value.
42 //!  - For types that implement `Default`, the `take` method replaces the current interior value
43 //!    with `Default::default()` and returns the replaced value.
44 //!  - For all types, the `replace` method replaces the current interior value and returns the
45 //!    replaced value and the `into_inner` method consumes the `Cell<T>` and returns the interior
46 //!    value. Additionally, the `set` method replaces the interior value, dropping the replaced
47 //!    value.
48 //!
49 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
50 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
51 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
52 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
53 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
54 //! panic.
55 //!
56 //! # When to choose interior mutability
57 //!
58 //! The more common inherited mutability, where one must have unique access to mutate a value, is
59 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
60 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
61 //! interior mutability is something of a last resort. Since cell types enable mutation where it
62 //! would otherwise be disallowed though, there are occasions when interior mutability might be
63 //! appropriate, or even *must* be used, e.g.
64 //!
65 //! * Introducing mutability 'inside' of something immutable
66 //! * Implementation details of logically-immutable methods.
67 //! * Mutating implementations of `Clone`.
68 //!
69 //! ## Introducing mutability 'inside' of something immutable
70 //!
71 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
72 //! cloned and shared between multiple parties. Because the contained values may be
73 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
74 //! impossible to mutate data inside of these smart pointers at all.
75 //!
76 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
77 //! mutability:
78 //!
79 //! ```
80 //! use std::collections::HashMap;
81 //! use std::cell::RefCell;
82 //! use std::rc::Rc;
83 //!
84 //! fn main() {
85 //!     let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
86 //!     shared_map.borrow_mut().insert("africa", 92388);
87 //!     shared_map.borrow_mut().insert("kyoto", 11837);
88 //!     shared_map.borrow_mut().insert("piccadilly", 11826);
89 //!     shared_map.borrow_mut().insert("marbles", 38);
90 //! }
91 //! ```
92 //!
93 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
94 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
95 //! multi-threaded situation.
96 //!
97 //! ## Implementation details of logically-immutable methods
98 //!
99 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
100 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
101 //! forces the implementation to perform mutation; or because you must employ mutation to implement
102 //! a trait method that was originally defined to take `&self`.
103 //!
104 //! ```
105 //! # #![allow(dead_code)]
106 //! use std::cell::RefCell;
107 //!
108 //! struct Graph {
109 //!     edges: Vec<(i32, i32)>,
110 //!     span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
111 //! }
112 //!
113 //! impl Graph {
114 //!     fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
115 //!         // Create a new scope to contain the lifetime of the
116 //!         // dynamic borrow
117 //!         {
118 //!             // Take a reference to the inside of cache cell
119 //!             let mut cache = self.span_tree_cache.borrow_mut();
120 //!             if cache.is_some() {
121 //!                 return cache.as_ref().unwrap().clone();
122 //!             }
123 //!
124 //!             let span_tree = self.calc_span_tree();
125 //!             *cache = Some(span_tree);
126 //!         }
127 //!
128 //!         // Recursive call to return the just-cached value.
129 //!         // Note that if we had not let the previous borrow
130 //!         // of the cache fall out of scope then the subsequent
131 //!         // recursive borrow would cause a dynamic thread panic.
132 //!         // This is the major hazard of using `RefCell`.
133 //!         self.minimum_spanning_tree()
134 //!     }
135 //! #   fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
136 //! }
137 //! ```
138 //!
139 //! ## Mutating implementations of `Clone`
140 //!
141 //! This is simply a special - but common - case of the previous: hiding mutability for operations
142 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
143 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
144 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
145 //! `Cell<T>`.
146 //!
147 //! ```
148 //! #![feature(core_intrinsics)]
149 //! #![feature(shared)]
150 //! use std::cell::Cell;
151 //! use std::ptr::Shared;
152 //! use std::intrinsics::abort;
153 //!
154 //! struct Rc<T: ?Sized> {
155 //!     ptr: Shared<RcBox<T>>
156 //! }
157 //!
158 //! struct RcBox<T: ?Sized> {
159 //!     strong: Cell<usize>,
160 //!     refcount: Cell<usize>,
161 //!     value: T,
162 //! }
163 //!
164 //! impl<T: ?Sized> Clone for Rc<T> {
165 //!     fn clone(&self) -> Rc<T> {
166 //!         self.inc_strong();
167 //!         Rc { ptr: self.ptr }
168 //!     }
169 //! }
170 //!
171 //! trait RcBoxPtr<T: ?Sized> {
172 //!
173 //!     fn inner(&self) -> &RcBox<T>;
174 //!
175 //!     fn strong(&self) -> usize {
176 //!         self.inner().strong.get()
177 //!     }
178 //!
179 //!     fn inc_strong(&self) {
180 //!         self.inner()
181 //!             .strong
182 //!             .set(self.strong()
183 //!                      .checked_add(1)
184 //!                      .unwrap_or_else(|| unsafe { abort() }));
185 //!     }
186 //! }
187 //!
188 //! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> {
189 //!    fn inner(&self) -> &RcBox<T> {
190 //!        unsafe {
191 //!            self.ptr.as_ref()
192 //!        }
193 //!    }
194 //! }
195 //! ```
196 //!
197
198 #![stable(feature = "rust1", since = "1.0.0")]
199
200 use cmp::Ordering;
201 use fmt::{self, Debug, Display};
202 use marker::Unsize;
203 use mem;
204 use ops::{Deref, DerefMut, CoerceUnsized};
205 use ptr;
206
207 /// A mutable memory location.
208 ///
209 /// # Examples
210 ///
211 /// Here you can see how using `Cell<T>` allows to use mutable field inside
212 /// immutable struct (which is also called 'interior mutability').
213 ///
214 /// ```
215 /// use std::cell::Cell;
216 ///
217 /// struct SomeStruct {
218 ///     regular_field: u8,
219 ///     special_field: Cell<u8>,
220 /// }
221 ///
222 /// let my_struct = SomeStruct {
223 ///     regular_field: 0,
224 ///     special_field: Cell::new(1),
225 /// };
226 ///
227 /// let new_value = 100;
228 ///
229 /// // ERROR, because my_struct is immutable
230 /// // my_struct.regular_field = new_value;
231 ///
232 /// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
233 /// my_struct.special_field.set(new_value);
234 /// assert_eq!(my_struct.special_field.get(), new_value);
235 /// ```
236 ///
237 /// See the [module-level documentation](index.html) for more.
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub struct Cell<T> {
240     value: UnsafeCell<T>,
241 }
242
243 impl<T:Copy> Cell<T> {
244     /// Returns a copy of the contained value.
245     ///
246     /// # Examples
247     ///
248     /// ```
249     /// use std::cell::Cell;
250     ///
251     /// let c = Cell::new(5);
252     ///
253     /// let five = c.get();
254     /// ```
255     #[inline]
256     #[stable(feature = "rust1", since = "1.0.0")]
257     pub fn get(&self) -> T {
258         unsafe{ *self.value.get() }
259     }
260 }
261
262 #[stable(feature = "rust1", since = "1.0.0")]
263 unsafe impl<T> Send for Cell<T> where T: Send {}
264
265 #[stable(feature = "rust1", since = "1.0.0")]
266 impl<T> !Sync for Cell<T> {}
267
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<T:Copy> Clone for Cell<T> {
270     #[inline]
271     fn clone(&self) -> Cell<T> {
272         Cell::new(self.get())
273     }
274 }
275
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T:Default> Default for Cell<T> {
278     /// Creates a `Cell<T>`, with the `Default` value for T.
279     #[inline]
280     fn default() -> Cell<T> {
281         Cell::new(Default::default())
282     }
283 }
284
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
287     #[inline]
288     fn eq(&self, other: &Cell<T>) -> bool {
289         self.get() == other.get()
290     }
291 }
292
293 #[stable(feature = "cell_eq", since = "1.2.0")]
294 impl<T:Eq + Copy> Eq for Cell<T> {}
295
296 #[stable(feature = "cell_ord", since = "1.10.0")]
297 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
298     #[inline]
299     fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
300         self.get().partial_cmp(&other.get())
301     }
302
303     #[inline]
304     fn lt(&self, other: &Cell<T>) -> bool {
305         self.get() < other.get()
306     }
307
308     #[inline]
309     fn le(&self, other: &Cell<T>) -> bool {
310         self.get() <= other.get()
311     }
312
313     #[inline]
314     fn gt(&self, other: &Cell<T>) -> bool {
315         self.get() > other.get()
316     }
317
318     #[inline]
319     fn ge(&self, other: &Cell<T>) -> bool {
320         self.get() >= other.get()
321     }
322 }
323
324 #[stable(feature = "cell_ord", since = "1.10.0")]
325 impl<T:Ord + Copy> Ord for Cell<T> {
326     #[inline]
327     fn cmp(&self, other: &Cell<T>) -> Ordering {
328         self.get().cmp(&other.get())
329     }
330 }
331
332 #[stable(feature = "cell_from", since = "1.12.0")]
333 impl<T> From<T> for Cell<T> {
334     fn from(t: T) -> Cell<T> {
335         Cell::new(t)
336     }
337 }
338
339 impl<T> Cell<T> {
340     /// Creates a new `Cell` containing the given value.
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// use std::cell::Cell;
346     ///
347     /// let c = Cell::new(5);
348     /// ```
349     #[stable(feature = "rust1", since = "1.0.0")]
350     #[inline]
351     pub const fn new(value: T) -> Cell<T> {
352         Cell {
353             value: UnsafeCell::new(value),
354         }
355     }
356
357     /// Returns a raw pointer to the underlying data in this cell.
358     ///
359     /// # Examples
360     ///
361     /// ```
362     /// use std::cell::Cell;
363     ///
364     /// let c = Cell::new(5);
365     ///
366     /// let ptr = c.as_ptr();
367     /// ```
368     #[inline]
369     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
370     pub fn as_ptr(&self) -> *mut T {
371         self.value.get()
372     }
373
374     /// Returns a mutable reference to the underlying data.
375     ///
376     /// This call borrows `Cell` mutably (at compile-time) which guarantees
377     /// that we possess the only reference.
378     ///
379     /// # Examples
380     ///
381     /// ```
382     /// use std::cell::Cell;
383     ///
384     /// let mut c = Cell::new(5);
385     /// *c.get_mut() += 1;
386     ///
387     /// assert_eq!(c.get(), 6);
388     /// ```
389     #[inline]
390     #[stable(feature = "cell_get_mut", since = "1.11.0")]
391     pub fn get_mut(&mut self) -> &mut T {
392         unsafe {
393             &mut *self.value.get()
394         }
395     }
396
397     /// Sets the contained value.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// use std::cell::Cell;
403     ///
404     /// let c = Cell::new(5);
405     ///
406     /// c.set(10);
407     /// ```
408     #[inline]
409     #[stable(feature = "rust1", since = "1.0.0")]
410     pub fn set(&self, val: T) {
411         let old = self.replace(val);
412         drop(old);
413     }
414
415     /// Swaps the values of two Cells.
416     /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// use std::cell::Cell;
422     ///
423     /// let c1 = Cell::new(5i32);
424     /// let c2 = Cell::new(10i32);
425     /// c1.swap(&c2);
426     /// assert_eq!(10, c1.get());
427     /// assert_eq!(5, c2.get());
428     /// ```
429     #[inline]
430     #[stable(feature = "move_cell", since = "1.17.0")]
431     pub fn swap(&self, other: &Self) {
432         if ptr::eq(self, other) {
433             return;
434         }
435         unsafe {
436             ptr::swap(self.value.get(), other.value.get());
437         }
438     }
439
440     /// Replaces the contained value, and returns it.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// use std::cell::Cell;
446     ///
447     /// let cell = Cell::new(5);
448     /// assert_eq!(cell.get(), 5);
449     /// assert_eq!(cell.replace(10), 5);
450     /// assert_eq!(cell.get(), 10);
451     /// ```
452     #[stable(feature = "move_cell", since = "1.17.0")]
453     pub fn replace(&self, val: T) -> T {
454         mem::replace(unsafe { &mut *self.value.get() }, val)
455     }
456
457     /// Unwraps the value.
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// use std::cell::Cell;
463     ///
464     /// let c = Cell::new(5);
465     /// let five = c.into_inner();
466     ///
467     /// assert_eq!(five, 5);
468     /// ```
469     #[stable(feature = "move_cell", since = "1.17.0")]
470     pub fn into_inner(self) -> T {
471         self.value.into_inner()
472     }
473 }
474
475 impl<T: Default> Cell<T> {
476     /// Takes the value of the cell, leaving `Default::default()` in its place.
477     ///
478     /// # Examples
479     ///
480     /// ```
481     /// use std::cell::Cell;
482     ///
483     /// let c = Cell::new(5);
484     /// let five = c.take();
485     ///
486     /// assert_eq!(five, 5);
487     /// assert_eq!(c.into_inner(), 0);
488     /// ```
489     #[stable(feature = "move_cell", since = "1.17.0")]
490     pub fn take(&self) -> T {
491         self.replace(Default::default())
492     }
493 }
494
495 #[unstable(feature = "coerce_unsized", issue = "27732")]
496 impl<T: CoerceUnsized<U>, U> CoerceUnsized<Cell<U>> for Cell<T> {}
497
498 /// A mutable memory location with dynamically checked borrow rules
499 ///
500 /// See the [module-level documentation](index.html) for more.
501 #[stable(feature = "rust1", since = "1.0.0")]
502 pub struct RefCell<T: ?Sized> {
503     borrow: Cell<BorrowFlag>,
504     value: UnsafeCell<T>,
505 }
506
507 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
508 #[stable(feature = "try_borrow", since = "1.13.0")]
509 pub struct BorrowError {
510     _private: (),
511 }
512
513 #[stable(feature = "try_borrow", since = "1.13.0")]
514 impl Debug for BorrowError {
515     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516         f.debug_struct("BorrowError").finish()
517     }
518 }
519
520 #[stable(feature = "try_borrow", since = "1.13.0")]
521 impl Display for BorrowError {
522     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523         Display::fmt("already mutably borrowed", f)
524     }
525 }
526
527 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
528 #[stable(feature = "try_borrow", since = "1.13.0")]
529 pub struct BorrowMutError {
530     _private: (),
531 }
532
533 #[stable(feature = "try_borrow", since = "1.13.0")]
534 impl Debug for BorrowMutError {
535     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536         f.debug_struct("BorrowMutError").finish()
537     }
538 }
539
540 #[stable(feature = "try_borrow", since = "1.13.0")]
541 impl Display for BorrowMutError {
542     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
543         Display::fmt("already borrowed", f)
544     }
545 }
546
547 // Values [1, MAX-1] represent the number of `Ref` active
548 // (will not outgrow its range since `usize` is the size of the address space)
549 type BorrowFlag = usize;
550 const UNUSED: BorrowFlag = 0;
551 const WRITING: BorrowFlag = !0;
552
553 impl<T> RefCell<T> {
554     /// Creates a new `RefCell` containing `value`.
555     ///
556     /// # Examples
557     ///
558     /// ```
559     /// use std::cell::RefCell;
560     ///
561     /// let c = RefCell::new(5);
562     /// ```
563     #[stable(feature = "rust1", since = "1.0.0")]
564     #[inline]
565     pub const fn new(value: T) -> RefCell<T> {
566         RefCell {
567             value: UnsafeCell::new(value),
568             borrow: Cell::new(UNUSED),
569         }
570     }
571
572     /// Consumes the `RefCell`, returning the wrapped value.
573     ///
574     /// # Examples
575     ///
576     /// ```
577     /// use std::cell::RefCell;
578     ///
579     /// let c = RefCell::new(5);
580     ///
581     /// let five = c.into_inner();
582     /// ```
583     #[stable(feature = "rust1", since = "1.0.0")]
584     #[inline]
585     pub fn into_inner(self) -> T {
586         // Since this function takes `self` (the `RefCell`) by value, the
587         // compiler statically verifies that it is not currently borrowed.
588         // Therefore the following assertion is just a `debug_assert!`.
589         debug_assert!(self.borrow.get() == UNUSED);
590         self.value.into_inner()
591     }
592
593     /// Replaces the wrapped value with a new one, returning the old value,
594     /// without deinitializing either one.
595     ///
596     /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
597     ///
598     /// # Panics
599     ///
600     /// Panics if the value is currently borrowed.
601     ///
602     /// # Examples
603     ///
604     /// ```
605     /// use std::cell::RefCell;
606     /// let cell = RefCell::new(5);
607     /// let old_value = cell.replace(6);
608     /// assert_eq!(old_value, 5);
609     /// assert_eq!(cell, RefCell::new(6));
610     /// ```
611     #[inline]
612     #[stable(feature = "refcell_replace", since="1.24.0")]
613     pub fn replace(&self, t: T) -> T {
614         mem::replace(&mut *self.borrow_mut(), t)
615     }
616
617     /// Replaces the wrapped value with a new one computed from `f`, returning
618     /// the old value, without deinitializing either one.
619     ///
620     /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
621     ///
622     /// # Panics
623     ///
624     /// Panics if the value is currently borrowed.
625     ///
626     /// # Examples
627     ///
628     /// ```
629     /// #![feature(refcell_replace_swap)]
630     /// use std::cell::RefCell;
631     /// let cell = RefCell::new(5);
632     /// let old_value = cell.replace_with(|&mut old| old + 1);
633     /// assert_eq!(old_value, 5);
634     /// assert_eq!(cell, RefCell::new(6));
635     /// ```
636     #[inline]
637     #[unstable(feature = "refcell_replace_swap", issue="43570")]
638     pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
639         let mut_borrow = &mut *self.borrow_mut();
640         let replacement = f(mut_borrow);
641         mem::replace(mut_borrow, replacement)
642     }
643
644     /// Swaps the wrapped value of `self` with the wrapped value of `other`,
645     /// without deinitializing either one.
646     ///
647     /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
648     ///
649     /// # Panics
650     ///
651     /// Panics if the value in either `RefCell` is currently borrowed.
652     ///
653     /// # Examples
654     ///
655     /// ```
656     /// use std::cell::RefCell;
657     /// let c = RefCell::new(5);
658     /// let d = RefCell::new(6);
659     /// c.swap(&d);
660     /// assert_eq!(c, RefCell::new(6));
661     /// assert_eq!(d, RefCell::new(5));
662     /// ```
663     #[inline]
664     #[stable(feature = "refcell_swap", since="1.24.0")]
665     pub fn swap(&self, other: &Self) {
666         mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
667     }
668 }
669
670 impl<T: ?Sized> RefCell<T> {
671     /// Immutably borrows the wrapped value.
672     ///
673     /// The borrow lasts until the returned `Ref` exits scope. Multiple
674     /// immutable borrows can be taken out at the same time.
675     ///
676     /// # Panics
677     ///
678     /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
679     /// [`try_borrow`](#method.try_borrow).
680     ///
681     /// # Examples
682     ///
683     /// ```
684     /// use std::cell::RefCell;
685     ///
686     /// let c = RefCell::new(5);
687     ///
688     /// let borrowed_five = c.borrow();
689     /// let borrowed_five2 = c.borrow();
690     /// ```
691     ///
692     /// An example of panic:
693     ///
694     /// ```
695     /// use std::cell::RefCell;
696     /// use std::thread;
697     ///
698     /// let result = thread::spawn(move || {
699     ///    let c = RefCell::new(5);
700     ///    let m = c.borrow_mut();
701     ///
702     ///    let b = c.borrow(); // this causes a panic
703     /// }).join();
704     ///
705     /// assert!(result.is_err());
706     /// ```
707     #[stable(feature = "rust1", since = "1.0.0")]
708     #[inline]
709     pub fn borrow(&self) -> Ref<T> {
710         self.try_borrow().expect("already mutably borrowed")
711     }
712
713     /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
714     /// borrowed.
715     ///
716     /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
717     /// taken out at the same time.
718     ///
719     /// This is the non-panicking variant of [`borrow`](#method.borrow).
720     ///
721     /// # Examples
722     ///
723     /// ```
724     /// use std::cell::RefCell;
725     ///
726     /// let c = RefCell::new(5);
727     ///
728     /// {
729     ///     let m = c.borrow_mut();
730     ///     assert!(c.try_borrow().is_err());
731     /// }
732     ///
733     /// {
734     ///     let m = c.borrow();
735     ///     assert!(c.try_borrow().is_ok());
736     /// }
737     /// ```
738     #[stable(feature = "try_borrow", since = "1.13.0")]
739     #[inline]
740     pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError> {
741         match BorrowRef::new(&self.borrow) {
742             Some(b) => Ok(Ref {
743                 value: unsafe { &*self.value.get() },
744                 borrow: b,
745             }),
746             None => Err(BorrowError { _private: () }),
747         }
748     }
749
750     /// Mutably borrows the wrapped value.
751     ///
752     /// The borrow lasts until the returned `RefMut` exits scope. The value
753     /// cannot be borrowed while this borrow is active.
754     ///
755     /// # Panics
756     ///
757     /// Panics if the value is currently borrowed. For a non-panicking variant, use
758     /// [`try_borrow_mut`](#method.try_borrow_mut).
759     ///
760     /// # Examples
761     ///
762     /// ```
763     /// use std::cell::RefCell;
764     ///
765     /// let c = RefCell::new(5);
766     ///
767     /// *c.borrow_mut() = 7;
768     ///
769     /// assert_eq!(*c.borrow(), 7);
770     /// ```
771     ///
772     /// An example of panic:
773     ///
774     /// ```
775     /// use std::cell::RefCell;
776     /// use std::thread;
777     ///
778     /// let result = thread::spawn(move || {
779     ///    let c = RefCell::new(5);
780     ///    let m = c.borrow();
781     ///
782     ///    let b = c.borrow_mut(); // this causes a panic
783     /// }).join();
784     ///
785     /// assert!(result.is_err());
786     /// ```
787     #[stable(feature = "rust1", since = "1.0.0")]
788     #[inline]
789     pub fn borrow_mut(&self) -> RefMut<T> {
790         self.try_borrow_mut().expect("already borrowed")
791     }
792
793     /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
794     ///
795     /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
796     /// while this borrow is active.
797     ///
798     /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
799     ///
800     /// # Examples
801     ///
802     /// ```
803     /// use std::cell::RefCell;
804     ///
805     /// let c = RefCell::new(5);
806     ///
807     /// {
808     ///     let m = c.borrow();
809     ///     assert!(c.try_borrow_mut().is_err());
810     /// }
811     ///
812     /// assert!(c.try_borrow_mut().is_ok());
813     /// ```
814     #[stable(feature = "try_borrow", since = "1.13.0")]
815     #[inline]
816     pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError> {
817         match BorrowRefMut::new(&self.borrow) {
818             Some(b) => Ok(RefMut {
819                 value: unsafe { &mut *self.value.get() },
820                 borrow: b,
821             }),
822             None => Err(BorrowMutError { _private: () }),
823         }
824     }
825
826     /// Returns a raw pointer to the underlying data in this cell.
827     ///
828     /// # Examples
829     ///
830     /// ```
831     /// use std::cell::RefCell;
832     ///
833     /// let c = RefCell::new(5);
834     ///
835     /// let ptr = c.as_ptr();
836     /// ```
837     #[inline]
838     #[stable(feature = "cell_as_ptr", since = "1.12.0")]
839     pub fn as_ptr(&self) -> *mut T {
840         self.value.get()
841     }
842
843     /// Returns a mutable reference to the underlying data.
844     ///
845     /// This call borrows `RefCell` mutably (at compile-time) so there is no
846     /// need for dynamic checks.
847     ///
848     /// However be cautious: this method expects `self` to be mutable, which is
849     /// generally not the case when using a `RefCell`. Take a look at the
850     /// [`borrow_mut`] method instead if `self` isn't mutable.
851     ///
852     /// Also, please be aware that this method is only for special circumstances and is usually
853     /// not what you want. In case of doubt, use [`borrow_mut`] instead.
854     ///
855     /// [`borrow_mut`]: #method.borrow_mut
856     ///
857     /// # Examples
858     ///
859     /// ```
860     /// use std::cell::RefCell;
861     ///
862     /// let mut c = RefCell::new(5);
863     /// *c.get_mut() += 1;
864     ///
865     /// assert_eq!(c, RefCell::new(6));
866     /// ```
867     #[inline]
868     #[stable(feature = "cell_get_mut", since = "1.11.0")]
869     pub fn get_mut(&mut self) -> &mut T {
870         unsafe {
871             &mut *self.value.get()
872         }
873     }
874 }
875
876 #[stable(feature = "rust1", since = "1.0.0")]
877 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
878
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<T: ?Sized> !Sync for RefCell<T> {}
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<T: Clone> Clone for RefCell<T> {
884     /// # Panics
885     ///
886     /// Panics if the value is currently mutably borrowed.
887     #[inline]
888     fn clone(&self) -> RefCell<T> {
889         RefCell::new(self.borrow().clone())
890     }
891 }
892
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl<T:Default> Default for RefCell<T> {
895     /// Creates a `RefCell<T>`, with the `Default` value for T.
896     #[inline]
897     fn default() -> RefCell<T> {
898         RefCell::new(Default::default())
899     }
900 }
901
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
904     /// # Panics
905     ///
906     /// Panics if the value in either `RefCell` is currently borrowed.
907     #[inline]
908     fn eq(&self, other: &RefCell<T>) -> bool {
909         *self.borrow() == *other.borrow()
910     }
911 }
912
913 #[stable(feature = "cell_eq", since = "1.2.0")]
914 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
915
916 #[stable(feature = "cell_ord", since = "1.10.0")]
917 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
918     /// # Panics
919     ///
920     /// Panics if the value in either `RefCell` is currently borrowed.
921     #[inline]
922     fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
923         self.borrow().partial_cmp(&*other.borrow())
924     }
925
926     /// # Panics
927     ///
928     /// Panics if the value in either `RefCell` is currently borrowed.
929     #[inline]
930     fn lt(&self, other: &RefCell<T>) -> bool {
931         *self.borrow() < *other.borrow()
932     }
933
934     /// # Panics
935     ///
936     /// Panics if the value in either `RefCell` is currently borrowed.
937     #[inline]
938     fn le(&self, other: &RefCell<T>) -> bool {
939         *self.borrow() <= *other.borrow()
940     }
941
942     /// # Panics
943     ///
944     /// Panics if the value in either `RefCell` is currently borrowed.
945     #[inline]
946     fn gt(&self, other: &RefCell<T>) -> bool {
947         *self.borrow() > *other.borrow()
948     }
949
950     /// # Panics
951     ///
952     /// Panics if the value in either `RefCell` is currently borrowed.
953     #[inline]
954     fn ge(&self, other: &RefCell<T>) -> bool {
955         *self.borrow() >= *other.borrow()
956     }
957 }
958
959 #[stable(feature = "cell_ord", since = "1.10.0")]
960 impl<T: ?Sized + Ord> Ord for RefCell<T> {
961     /// # Panics
962     ///
963     /// Panics if the value in either `RefCell` is currently borrowed.
964     #[inline]
965     fn cmp(&self, other: &RefCell<T>) -> Ordering {
966         self.borrow().cmp(&*other.borrow())
967     }
968 }
969
970 #[stable(feature = "cell_from", since = "1.12.0")]
971 impl<T> From<T> for RefCell<T> {
972     fn from(t: T) -> RefCell<T> {
973         RefCell::new(t)
974     }
975 }
976
977 #[unstable(feature = "coerce_unsized", issue = "27732")]
978 impl<T: CoerceUnsized<U>, U> CoerceUnsized<RefCell<U>> for RefCell<T> {}
979
980 struct BorrowRef<'b> {
981     borrow: &'b Cell<BorrowFlag>,
982 }
983
984 impl<'b> BorrowRef<'b> {
985     #[inline]
986     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
987         match borrow.get() {
988             WRITING => None,
989             b => {
990                 borrow.set(b + 1);
991                 Some(BorrowRef { borrow: borrow })
992             },
993         }
994     }
995 }
996
997 impl<'b> Drop for BorrowRef<'b> {
998     #[inline]
999     fn drop(&mut self) {
1000         let borrow = self.borrow.get();
1001         debug_assert!(borrow != WRITING && borrow != UNUSED);
1002         self.borrow.set(borrow - 1);
1003     }
1004 }
1005
1006 impl<'b> Clone for BorrowRef<'b> {
1007     #[inline]
1008     fn clone(&self) -> BorrowRef<'b> {
1009         // Since this Ref exists, we know the borrow flag
1010         // is not set to WRITING.
1011         let borrow = self.borrow.get();
1012         debug_assert!(borrow != UNUSED);
1013         // Prevent the borrow counter from overflowing.
1014         assert!(borrow != WRITING);
1015         self.borrow.set(borrow + 1);
1016         BorrowRef { borrow: self.borrow }
1017     }
1018 }
1019
1020 /// Wraps a borrowed reference to a value in a `RefCell` box.
1021 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
1022 ///
1023 /// See the [module-level documentation](index.html) for more.
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 pub struct Ref<'b, T: ?Sized + 'b> {
1026     value: &'b T,
1027     borrow: BorrowRef<'b>,
1028 }
1029
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
1032     type Target = T;
1033
1034     #[inline]
1035     fn deref(&self) -> &T {
1036         self.value
1037     }
1038 }
1039
1040 impl<'b, T: ?Sized> Ref<'b, T> {
1041     /// Copies a `Ref`.
1042     ///
1043     /// The `RefCell` is already immutably borrowed, so this cannot fail.
1044     ///
1045     /// This is an associated function that needs to be used as
1046     /// `Ref::clone(...)`.  A `Clone` implementation or a method would interfere
1047     /// with the widespread use of `r.borrow().clone()` to clone the contents of
1048     /// a `RefCell`.
1049     #[stable(feature = "cell_extras", since = "1.15.0")]
1050     #[inline]
1051     pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
1052         Ref {
1053             value: orig.value,
1054             borrow: orig.borrow.clone(),
1055         }
1056     }
1057
1058     /// Make a new `Ref` for a component of the borrowed data.
1059     ///
1060     /// The `RefCell` is already immutably borrowed, so this cannot fail.
1061     ///
1062     /// This is an associated function that needs to be used as `Ref::map(...)`.
1063     /// A method would interfere with methods of the same name on the contents
1064     /// of a `RefCell` used through `Deref`.
1065     ///
1066     /// # Examples
1067     ///
1068     /// ```
1069     /// use std::cell::{RefCell, Ref};
1070     ///
1071     /// let c = RefCell::new((5, 'b'));
1072     /// let b1: Ref<(u32, char)> = c.borrow();
1073     /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
1074     /// assert_eq!(*b2, 5)
1075     /// ```
1076     #[stable(feature = "cell_map", since = "1.8.0")]
1077     #[inline]
1078     pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
1079         where F: FnOnce(&T) -> &U
1080     {
1081         Ref {
1082             value: f(orig.value),
1083             borrow: orig.borrow,
1084         }
1085     }
1086 }
1087
1088 #[unstable(feature = "coerce_unsized", issue = "27732")]
1089 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
1090
1091 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1092 impl<'a, T: ?Sized + fmt::Display> fmt::Display for Ref<'a, T> {
1093     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1094         self.value.fmt(f)
1095     }
1096 }
1097
1098 impl<'b, T: ?Sized> RefMut<'b, T> {
1099     /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
1100     /// variant.
1101     ///
1102     /// The `RefCell` is already mutably borrowed, so this cannot fail.
1103     ///
1104     /// This is an associated function that needs to be used as
1105     /// `RefMut::map(...)`.  A method would interfere with methods of the same
1106     /// name on the contents of a `RefCell` used through `Deref`.
1107     ///
1108     /// # Examples
1109     ///
1110     /// ```
1111     /// use std::cell::{RefCell, RefMut};
1112     ///
1113     /// let c = RefCell::new((5, 'b'));
1114     /// {
1115     ///     let b1: RefMut<(u32, char)> = c.borrow_mut();
1116     ///     let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
1117     ///     assert_eq!(*b2, 5);
1118     ///     *b2 = 42;
1119     /// }
1120     /// assert_eq!(*c.borrow(), (42, 'b'));
1121     /// ```
1122     #[stable(feature = "cell_map", since = "1.8.0")]
1123     #[inline]
1124     pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
1125         where F: FnOnce(&mut T) -> &mut U
1126     {
1127         // FIXME(nll-rfc#40): fix borrow-check
1128         let RefMut { value, borrow } = orig;
1129         RefMut {
1130             value: f(value),
1131             borrow: borrow,
1132         }
1133     }
1134 }
1135
1136 struct BorrowRefMut<'b> {
1137     borrow: &'b Cell<BorrowFlag>,
1138 }
1139
1140 impl<'b> Drop for BorrowRefMut<'b> {
1141     #[inline]
1142     fn drop(&mut self) {
1143         let borrow = self.borrow.get();
1144         debug_assert!(borrow == WRITING);
1145         self.borrow.set(UNUSED);
1146     }
1147 }
1148
1149 impl<'b> BorrowRefMut<'b> {
1150     #[inline]
1151     fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
1152         match borrow.get() {
1153             UNUSED => {
1154                 borrow.set(WRITING);
1155                 Some(BorrowRefMut { borrow: borrow })
1156             },
1157             _ => None,
1158         }
1159     }
1160 }
1161
1162 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
1163 ///
1164 /// See the [module-level documentation](index.html) for more.
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub struct RefMut<'b, T: ?Sized + 'b> {
1167     value: &'b mut T,
1168     borrow: BorrowRefMut<'b>,
1169 }
1170
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1173     type Target = T;
1174
1175     #[inline]
1176     fn deref(&self) -> &T {
1177         self.value
1178     }
1179 }
1180
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1183     #[inline]
1184     fn deref_mut(&mut self) -> &mut T {
1185         self.value
1186     }
1187 }
1188
1189 #[unstable(feature = "coerce_unsized", issue = "27732")]
1190 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1191
1192 #[stable(feature = "std_guard_impls", since = "1.20.0")]
1193 impl<'a, T: ?Sized + fmt::Display> fmt::Display for RefMut<'a, T> {
1194     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1195         self.value.fmt(f)
1196     }
1197 }
1198
1199 /// The core primitive for interior mutability in Rust.
1200 ///
1201 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1202 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1203 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1204 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1205 ///
1206 /// If you have a reference `&SomeStruct`, then normally in Rust all fields of `SomeStruct` are
1207 /// immutable. The compiler makes optimizations based on the knowledge that `&T` is not mutably
1208 /// aliased or mutated, and that `&mut T` is unique. `UnsafeCel<T>` is the only core language
1209 /// feature to work around this restriction. All other types that allow internal mutability, such as
1210 /// `Cell<T>` and `RefCell<T>` use `UnsafeCell` to wrap their internal data.
1211 ///
1212 /// The `UnsafeCell` API itself is technically very simple: it gives you a raw pointer `*mut T` to
1213 /// its contents. It is up to _you_ as the abstraction designer to use that raw pointer correctly.
1214 ///
1215 /// The precise Rust aliasing rules are somewhat in flux, but the main points are not contentious:
1216 ///
1217 /// - If you create a safe reference with lifetime `'a` (either a `&T` or `&mut T` reference) that
1218 /// is accessible by safe code (for example, because you returned it), then you must not access
1219 /// the data in any way that contradicts that reference for the remainder of `'a`. For example, that
1220 /// means that if you take the `*mut T` from an `UnsafeCell<T>` and case it to an `&T`, then until
1221 /// that reference's lifetime expires, the data in `T` must remain immutable (modulo any
1222 /// `UnsafeCell` data found within `T`, of course). Similarly, if you create an `&mut T` reference
1223 /// that is released to safe code, then you must not access the data within the `UnsafeCell` until
1224 /// that reference expires.
1225 ///
1226 /// - At all times, you must avoid data races, meaning that if multiple threads have access to
1227 /// the same `UnsafeCell`, then any writes must have a proper happens-before relation to all other
1228 /// accesses (or use atomics).
1229 ///
1230 /// To assist with proper design, the following scenarios are explicitly declared legal
1231 /// for single-threaded code:
1232 ///
1233 /// 1. A `&T` reference can be released to safe code and there it can co-exit with other `&T`
1234 /// references, but not with a `&mut T`
1235 ///
1236 /// 2. A `&mut T` reference may be released to safe code, provided neither other `&mut T` nor `&T`
1237 /// co-exist with it. A `&mut T` must always be unique.
1238 ///
1239 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1240 /// okay (provided you enforce the invariants some other way), it is still undefined behavior
1241 /// to have multiple `&mut UnsafeCell<T>` aliases.
1242 ///
1243 /// # Examples
1244 ///
1245 /// ```
1246 /// use std::cell::UnsafeCell;
1247 /// use std::marker::Sync;
1248 ///
1249 /// # #[allow(dead_code)]
1250 /// struct NotThreadSafe<T> {
1251 ///     value: UnsafeCell<T>,
1252 /// }
1253 ///
1254 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1255 /// ```
1256 #[lang = "unsafe_cell"]
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 pub struct UnsafeCell<T: ?Sized> {
1259     value: T,
1260 }
1261
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1264
1265 impl<T> UnsafeCell<T> {
1266     /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1267     /// value.
1268     ///
1269     /// All access to the inner value through methods is `unsafe`.
1270     ///
1271     /// # Examples
1272     ///
1273     /// ```
1274     /// use std::cell::UnsafeCell;
1275     ///
1276     /// let uc = UnsafeCell::new(5);
1277     /// ```
1278     #[stable(feature = "rust1", since = "1.0.0")]
1279     #[inline]
1280     pub const fn new(value: T) -> UnsafeCell<T> {
1281         UnsafeCell { value: value }
1282     }
1283
1284     /// Unwraps the value.
1285     ///
1286     /// # Examples
1287     ///
1288     /// ```
1289     /// use std::cell::UnsafeCell;
1290     ///
1291     /// let uc = UnsafeCell::new(5);
1292     ///
1293     /// let five = uc.into_inner();
1294     /// ```
1295     #[inline]
1296     #[stable(feature = "rust1", since = "1.0.0")]
1297     pub fn into_inner(self) -> T {
1298         self.value
1299     }
1300 }
1301
1302 impl<T: ?Sized> UnsafeCell<T> {
1303     /// Gets a mutable pointer to the wrapped value.
1304     ///
1305     /// This can be cast to a pointer of any kind.
1306     /// Ensure that the access is unique (no active references, mutable or not)
1307     /// when casting to `&mut T`, and ensure that there are no mutations
1308     /// or mutable aliases going on when casting to `&T`
1309     ///
1310     /// # Examples
1311     ///
1312     /// ```
1313     /// use std::cell::UnsafeCell;
1314     ///
1315     /// let uc = UnsafeCell::new(5);
1316     ///
1317     /// let five = uc.get();
1318     /// ```
1319     #[inline]
1320     #[stable(feature = "rust1", since = "1.0.0")]
1321     pub fn get(&self) -> *mut T {
1322         &self.value as *const T as *mut T
1323     }
1324 }
1325
1326 #[stable(feature = "unsafe_cell_default", since = "1.10.0")]
1327 impl<T: Default> Default for UnsafeCell<T> {
1328     /// Creates an `UnsafeCell`, with the `Default` value for T.
1329     fn default() -> UnsafeCell<T> {
1330         UnsafeCell::new(Default::default())
1331     }
1332 }
1333
1334 #[stable(feature = "cell_from", since = "1.12.0")]
1335 impl<T> From<T> for UnsafeCell<T> {
1336     fn from(t: T) -> UnsafeCell<T> {
1337         UnsafeCell::new(t)
1338     }
1339 }
1340
1341 #[unstable(feature = "coerce_unsized", issue = "27732")]
1342 impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafeCell<U>> for UnsafeCell<T> {}
1343
1344 #[allow(unused)]
1345 fn assert_coerce_unsized(a: UnsafeCell<&i32>, b: Cell<&i32>, c: RefCell<&i32>) {
1346     let _: UnsafeCell<&Send> = a;
1347     let _: Cell<&Send> = b;
1348     let _: RefCell<&Send> = c;
1349 }