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.
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.
11 //! Shareable mutable containers.
13 //! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
14 //! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
15 //! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
16 //! with typical Rust types that exhibit 'inherited mutability'.
18 //! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set`
19 //! methods that change the interior value with a single method call. `Cell<T>` though is only
20 //! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>`
21 //! type, acquiring a write lock before mutating.
23 //! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
24 //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
25 //! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
26 //! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
27 //! to borrow a value that is already mutably borrowed; when this happens it results in thread
30 //! # When to choose interior mutability
32 //! The more common inherited mutability, where one must have unique access to mutate a value, is
33 //! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
34 //! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
35 //! interior mutability is something of a last resort. Since cell types enable mutation where it
36 //! would otherwise be disallowed though, there are occasions when interior mutability might be
37 //! appropriate, or even *must* be used, e.g.
39 //! * Introducing mutability 'inside' of something immutable
40 //! * Implementation details of logically-immutable methods.
41 //! * Mutating implementations of `Clone`.
43 //! ## Introducing mutability 'inside' of something immutable
45 //! Many shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
46 //! cloned and shared between multiple parties. Because the contained values may be
47 //! multiply-aliased, they can only be borrowed with `&`, not `&mut`. Without cells it would be
48 //! impossible to mutate data inside of these smart pointers at all.
50 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
54 //! use std::collections::HashMap;
55 //! use std::cell::RefCell;
59 //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
60 //! shared_map.borrow_mut().insert("africa", 92388);
61 //! shared_map.borrow_mut().insert("kyoto", 11837);
62 //! shared_map.borrow_mut().insert("piccadilly", 11826);
63 //! shared_map.borrow_mut().insert("marbles", 38);
67 //! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
68 //! scenarios. Consider using `RwLock<T>` or `Mutex<T>` if you need shared mutability in a
69 //! multi-threaded situation.
71 //! ## Implementation details of logically-immutable methods
73 //! Occasionally it may be desirable not to expose in an API that there is mutation happening
74 //! "under the hood". This may be because logically the operation is immutable, but e.g. caching
75 //! forces the implementation to perform mutation; or because you must employ mutation to implement
76 //! a trait method that was originally defined to take `&self`.
79 //! # #![allow(dead_code)]
80 //! use std::cell::RefCell;
83 //! edges: Vec<(i32, i32)>,
84 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
88 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
89 //! // Create a new scope to contain the lifetime of the
92 //! // Take a reference to the inside of cache cell
93 //! let mut cache = self.span_tree_cache.borrow_mut();
94 //! if cache.is_some() {
95 //! return cache.as_ref().unwrap().clone();
98 //! let span_tree = self.calc_span_tree();
99 //! *cache = Some(span_tree);
102 //! // Recursive call to return the just-cached value.
103 //! // Note that if we had not let the previous borrow
104 //! // of the cache fall out of scope then the subsequent
105 //! // recursive borrow would cause a dynamic thread panic.
106 //! // This is the major hazard of using `RefCell`.
107 //! self.minimum_spanning_tree()
109 //! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
113 //! ## Mutating implementations of `Clone`
115 //! This is simply a special - but common - case of the previous: hiding mutability for operations
116 //! that appear to be immutable. The `clone` method is expected to not change the source value, and
117 //! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
118 //! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
122 //! use std::cell::Cell;
125 //! ptr: *mut RcBox<T>
128 //! struct RcBox<T> {
129 //! # #[allow(dead_code)]
131 //! refcount: Cell<usize>
134 //! impl<T> Clone for Rc<T> {
135 //! fn clone(&self) -> Rc<T> {
137 //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
138 //! Rc { ptr: self.ptr }
145 #![stable(feature = "rust1", since = "1.0.0")]
148 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
149 use default::Default;
150 use marker::{Copy, Send, Sync, Sized, Unsize};
151 use ops::{Deref, DerefMut, Drop, FnOnce, CoerceUnsized};
153 use option::Option::{None, Some};
155 /// A mutable memory location that admits only `Copy` data.
157 /// See the [module-level documentation](index.html) for more.
158 #[stable(feature = "rust1", since = "1.0.0")]
160 value: UnsafeCell<T>,
163 impl<T:Copy> Cell<T> {
164 /// Creates a new `Cell` containing the given value.
169 /// use std::cell::Cell;
171 /// let c = Cell::new(5);
173 #[stable(feature = "rust1", since = "1.0.0")]
175 pub const fn new(value: T) -> Cell<T> {
177 value: UnsafeCell::new(value),
181 /// Returns a copy of the contained value.
186 /// use std::cell::Cell;
188 /// let c = Cell::new(5);
190 /// let five = c.get();
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn get(&self) -> T {
195 unsafe{ *self.value.get() }
198 /// Sets the contained value.
203 /// use std::cell::Cell;
205 /// let c = Cell::new(5);
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub fn set(&self, value: T) {
213 *self.value.get() = value;
217 /// Returns a reference to the underlying `UnsafeCell`.
222 /// #![feature(as_unsafe_cell)]
224 /// use std::cell::Cell;
226 /// let c = Cell::new(5);
228 /// let uc = c.as_unsafe_cell();
231 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
232 pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
236 /// Returns a mutable reference to the underlying data.
238 /// This call borrows `Cell` mutably (at compile-time) which guarantees
239 /// that we possess the only reference.
244 /// use std::cell::Cell;
246 /// let mut c = Cell::new(5);
247 /// *c.get_mut() += 1;
249 /// assert_eq!(c.get(), 6);
252 #[stable(feature = "cell_get_mut", since = "1.11.0")]
253 pub fn get_mut(&mut self) -> &mut T {
255 &mut *self.value.get()
260 #[stable(feature = "rust1", since = "1.0.0")]
261 unsafe impl<T> Send for Cell<T> where T: Send {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T> !Sync for Cell<T> {}
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T:Copy> Clone for Cell<T> {
269 fn clone(&self) -> Cell<T> {
270 Cell::new(self.get())
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl<T:Default + Copy> Default for Cell<T> {
277 fn default() -> Cell<T> {
278 Cell::new(Default::default())
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
285 fn eq(&self, other: &Cell<T>) -> bool {
286 self.get() == other.get()
290 #[stable(feature = "cell_eq", since = "1.2.0")]
291 impl<T:Eq + Copy> Eq for Cell<T> {}
293 #[stable(feature = "cell_ord", since = "1.10.0")]
294 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
296 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
297 self.get().partial_cmp(&other.get())
301 fn lt(&self, other: &Cell<T>) -> bool {
302 self.get() < other.get()
306 fn le(&self, other: &Cell<T>) -> bool {
307 self.get() <= other.get()
311 fn gt(&self, other: &Cell<T>) -> bool {
312 self.get() > other.get()
316 fn ge(&self, other: &Cell<T>) -> bool {
317 self.get() >= other.get()
321 #[stable(feature = "cell_ord", since = "1.10.0")]
322 impl<T:Ord + Copy> Ord for Cell<T> {
324 fn cmp(&self, other: &Cell<T>) -> Ordering {
325 self.get().cmp(&other.get())
329 /// A mutable memory location with dynamically checked borrow rules
331 /// See the [module-level documentation](index.html) for more.
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub struct RefCell<T: ?Sized> {
334 borrow: Cell<BorrowFlag>,
335 value: UnsafeCell<T>,
338 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
339 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
340 #[unstable(feature = "borrow_state", issue = "27733")]
341 pub enum BorrowState {
342 /// The cell is currently being read, there is at least one active `borrow`.
344 /// The cell is currently being written to, there is an active `borrow_mut`.
346 /// There are no outstanding borrows on this cell.
350 // Values [1, MAX-1] represent the number of `Ref` active
351 // (will not outgrow its range since `usize` is the size of the address space)
352 type BorrowFlag = usize;
353 const UNUSED: BorrowFlag = 0;
354 const WRITING: BorrowFlag = !0;
357 /// Creates a new `RefCell` containing `value`.
362 /// use std::cell::RefCell;
364 /// let c = RefCell::new(5);
366 #[stable(feature = "rust1", since = "1.0.0")]
368 pub const fn new(value: T) -> RefCell<T> {
370 value: UnsafeCell::new(value),
371 borrow: Cell::new(UNUSED),
375 /// Consumes the `RefCell`, returning the wrapped value.
380 /// use std::cell::RefCell;
382 /// let c = RefCell::new(5);
384 /// let five = c.into_inner();
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn into_inner(self) -> T {
389 // Since this function takes `self` (the `RefCell`) by value, the
390 // compiler statically verifies that it is not currently borrowed.
391 // Therefore the following assertion is just a `debug_assert!`.
392 debug_assert!(self.borrow.get() == UNUSED);
393 unsafe { self.value.into_inner() }
397 impl<T: ?Sized> RefCell<T> {
398 /// Query the current state of this `RefCell`
400 /// The returned value can be dispatched on to determine if a call to
401 /// `borrow` or `borrow_mut` would succeed.
406 /// #![feature(borrow_state)]
408 /// use std::cell::{BorrowState, RefCell};
410 /// let c = RefCell::new(5);
412 /// match c.borrow_state() {
413 /// BorrowState::Writing => println!("Cannot be borrowed"),
414 /// BorrowState::Reading => println!("Cannot be borrowed mutably"),
415 /// BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
418 #[unstable(feature = "borrow_state", issue = "27733")]
420 pub fn borrow_state(&self) -> BorrowState {
421 match self.borrow.get() {
422 WRITING => BorrowState::Writing,
423 UNUSED => BorrowState::Unused,
424 _ => BorrowState::Reading,
428 /// Immutably borrows the wrapped value.
430 /// The borrow lasts until the returned `Ref` exits scope. Multiple
431 /// immutable borrows can be taken out at the same time.
435 /// Panics if the value is currently mutably borrowed.
440 /// use std::cell::RefCell;
442 /// let c = RefCell::new(5);
444 /// let borrowed_five = c.borrow();
445 /// let borrowed_five2 = c.borrow();
448 /// An example of panic:
451 /// use std::cell::RefCell;
454 /// let result = thread::spawn(move || {
455 /// let c = RefCell::new(5);
456 /// let m = c.borrow_mut();
458 /// let b = c.borrow(); // this causes a panic
461 /// assert!(result.is_err());
463 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn borrow(&self) -> Ref<T> {
466 match BorrowRef::new(&self.borrow) {
468 value: unsafe { &*self.value.get() },
471 None => panic!("RefCell<T> already mutably borrowed"),
475 /// Mutably borrows the wrapped value.
477 /// The borrow lasts until the returned `RefMut` exits scope. The value
478 /// cannot be borrowed while this borrow is active.
482 /// Panics if the value is currently borrowed.
487 /// use std::cell::RefCell;
489 /// let c = RefCell::new(5);
491 /// *c.borrow_mut() = 7;
493 /// assert_eq!(*c.borrow(), 7);
496 /// An example of panic:
499 /// use std::cell::RefCell;
502 /// let result = thread::spawn(move || {
503 /// let c = RefCell::new(5);
504 /// let m = c.borrow();
506 /// let b = c.borrow_mut(); // this causes a panic
509 /// assert!(result.is_err());
511 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn borrow_mut(&self) -> RefMut<T> {
514 match BorrowRefMut::new(&self.borrow) {
516 value: unsafe { &mut *self.value.get() },
519 None => panic!("RefCell<T> already borrowed"),
523 /// Returns a reference to the underlying `UnsafeCell`.
525 /// This can be used to circumvent `RefCell`'s safety checks.
527 /// This function is `unsafe` because `UnsafeCell`'s field is public.
532 /// #![feature(as_unsafe_cell)]
534 /// use std::cell::RefCell;
536 /// let c = RefCell::new(5);
537 /// let c = unsafe { c.as_unsafe_cell() };
540 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
541 pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
545 /// Returns a mutable reference to the underlying data.
547 /// This call borrows `RefCell` mutably (at compile-time) so there is no
548 /// need for dynamic checks.
553 /// use std::cell::RefCell;
555 /// let mut c = RefCell::new(5);
556 /// *c.get_mut() += 1;
558 /// assert_eq!(c, RefCell::new(6));
561 #[stable(feature = "cell_get_mut", since = "1.11.0")]
562 pub fn get_mut(&mut self) -> &mut T {
564 &mut *self.value.get()
569 #[stable(feature = "rust1", since = "1.0.0")]
570 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<T: ?Sized> !Sync for RefCell<T> {}
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<T: Clone> Clone for RefCell<T> {
578 fn clone(&self) -> RefCell<T> {
579 RefCell::new(self.borrow().clone())
583 #[stable(feature = "rust1", since = "1.0.0")]
584 impl<T:Default> Default for RefCell<T> {
586 fn default() -> RefCell<T> {
587 RefCell::new(Default::default())
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
594 fn eq(&self, other: &RefCell<T>) -> bool {
595 *self.borrow() == *other.borrow()
599 #[stable(feature = "cell_eq", since = "1.2.0")]
600 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
602 #[stable(feature = "cell_ord", since = "1.10.0")]
603 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
605 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
606 self.borrow().partial_cmp(&*other.borrow())
610 fn lt(&self, other: &RefCell<T>) -> bool {
611 *self.borrow() < *other.borrow()
615 fn le(&self, other: &RefCell<T>) -> bool {
616 *self.borrow() <= *other.borrow()
620 fn gt(&self, other: &RefCell<T>) -> bool {
621 *self.borrow() > *other.borrow()
625 fn ge(&self, other: &RefCell<T>) -> bool {
626 *self.borrow() >= *other.borrow()
630 #[stable(feature = "cell_ord", since = "1.10.0")]
631 impl<T: ?Sized + Ord> Ord for RefCell<T> {
633 fn cmp(&self, other: &RefCell<T>) -> Ordering {
634 self.borrow().cmp(&*other.borrow())
638 struct BorrowRef<'b> {
639 borrow: &'b Cell<BorrowFlag>,
642 impl<'b> BorrowRef<'b> {
644 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
649 Some(BorrowRef { borrow: borrow })
655 impl<'b> Drop for BorrowRef<'b> {
658 let borrow = self.borrow.get();
659 debug_assert!(borrow != WRITING && borrow != UNUSED);
660 self.borrow.set(borrow - 1);
664 impl<'b> Clone for BorrowRef<'b> {
666 fn clone(&self) -> BorrowRef<'b> {
667 // Since this Ref exists, we know the borrow flag
668 // is not set to WRITING.
669 let borrow = self.borrow.get();
670 debug_assert!(borrow != UNUSED);
671 // Prevent the borrow counter from overflowing.
672 assert!(borrow != WRITING);
673 self.borrow.set(borrow + 1);
674 BorrowRef { borrow: self.borrow }
678 /// Wraps a borrowed reference to a value in a `RefCell` box.
679 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
681 /// See the [module-level documentation](index.html) for more.
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub struct Ref<'b, T: ?Sized + 'b> {
685 borrow: BorrowRef<'b>,
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
693 fn deref(&self) -> &T {
698 impl<'b, T: ?Sized> Ref<'b, T> {
701 /// The `RefCell` is already immutably borrowed, so this cannot fail.
703 /// This is an associated function that needs to be used as
704 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
705 /// with the widespread use of `r.borrow().clone()` to clone the contents of
707 #[unstable(feature = "cell_extras",
708 reason = "likely to be moved to a method, pending language changes",
711 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
714 borrow: orig.borrow.clone(),
718 /// Make a new `Ref` for a component of the borrowed data.
720 /// The `RefCell` is already immutably borrowed, so this cannot fail.
722 /// This is an associated function that needs to be used as `Ref::map(...)`.
723 /// A method would interfere with methods of the same name on the contents
724 /// of a `RefCell` used through `Deref`.
729 /// use std::cell::{RefCell, Ref};
731 /// let c = RefCell::new((5, 'b'));
732 /// let b1: Ref<(u32, char)> = c.borrow();
733 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
734 /// assert_eq!(*b2, 5)
736 #[stable(feature = "cell_map", since = "1.8.0")]
738 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
739 where F: FnOnce(&T) -> &U
742 value: f(orig.value),
748 #[unstable(feature = "coerce_unsized", issue = "27732")]
749 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
751 impl<'b, T: ?Sized> RefMut<'b, T> {
752 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
755 /// The `RefCell` is already mutably borrowed, so this cannot fail.
757 /// This is an associated function that needs to be used as
758 /// `RefMut::map(...)`. A method would interfere with methods of the same
759 /// name on the contents of a `RefCell` used through `Deref`.
764 /// use std::cell::{RefCell, RefMut};
766 /// let c = RefCell::new((5, 'b'));
768 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
769 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
770 /// assert_eq!(*b2, 5);
773 /// assert_eq!(*c.borrow(), (42, 'b'));
775 #[stable(feature = "cell_map", since = "1.8.0")]
777 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
778 where F: FnOnce(&mut T) -> &mut U
781 value: f(orig.value),
787 struct BorrowRefMut<'b> {
788 borrow: &'b Cell<BorrowFlag>,
791 impl<'b> Drop for BorrowRefMut<'b> {
794 let borrow = self.borrow.get();
795 debug_assert!(borrow == WRITING);
796 self.borrow.set(UNUSED);
800 impl<'b> BorrowRefMut<'b> {
802 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
806 Some(BorrowRefMut { borrow: borrow })
813 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
815 /// See the [module-level documentation](index.html) for more.
816 #[stable(feature = "rust1", since = "1.0.0")]
817 pub struct RefMut<'b, T: ?Sized + 'b> {
819 borrow: BorrowRefMut<'b>,
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
827 fn deref(&self) -> &T {
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
835 fn deref_mut(&mut self) -> &mut T {
840 #[unstable(feature = "coerce_unsized", issue = "27732")]
841 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
843 /// The core primitive for interior mutability in Rust.
845 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
846 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
847 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
848 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
850 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
855 /// use std::cell::UnsafeCell;
856 /// use std::marker::Sync;
858 /// # #[allow(dead_code)]
859 /// struct NotThreadSafe<T> {
860 /// value: UnsafeCell<T>,
863 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
865 #[lang = "unsafe_cell"]
866 #[stable(feature = "rust1", since = "1.0.0")]
867 pub struct UnsafeCell<T: ?Sized> {
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
874 impl<T> UnsafeCell<T> {
875 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
878 /// All access to the inner value through methods is `unsafe`.
883 /// use std::cell::UnsafeCell;
885 /// let uc = UnsafeCell::new(5);
887 #[stable(feature = "rust1", since = "1.0.0")]
889 pub const fn new(value: T) -> UnsafeCell<T> {
890 UnsafeCell { value: value }
893 /// Unwraps the value.
897 /// This function is unsafe because this thread or another thread may currently be
898 /// inspecting the inner value.
903 /// use std::cell::UnsafeCell;
905 /// let uc = UnsafeCell::new(5);
907 /// let five = unsafe { uc.into_inner() };
910 #[stable(feature = "rust1", since = "1.0.0")]
911 pub unsafe fn into_inner(self) -> T {
916 impl<T: ?Sized> UnsafeCell<T> {
917 /// Gets a mutable pointer to the wrapped value.
922 /// use std::cell::UnsafeCell;
924 /// let uc = UnsafeCell::new(5);
926 /// let five = uc.get();
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub fn get(&self) -> *mut T {
931 &self.value as *const T as *mut T
935 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
936 impl<T: Default> Default for UnsafeCell<T> {
937 fn default() -> UnsafeCell<T> {
938 UnsafeCell::new(Default::default())