]> git.proxmox.com Git - rustc.git/blob - src/libcore/cell.rs
New upstream version 1.12.0+dfsg1
[rustc.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 //! 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'.
17 //!
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.
22 //!
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
28 //! panic.
29 //!
30 //! # When to choose interior mutability
31 //!
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.
38 //!
39 //! * Introducing mutability 'inside' of something immutable
40 //! * Implementation details of logically-immutable methods.
41 //! * Mutating implementations of `Clone`.
42 //!
43 //! ## Introducing mutability 'inside' of something immutable
44 //!
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.
49 //!
50 //! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
51 //! mutability:
52 //!
53 //! ```
54 //! use std::collections::HashMap;
55 //! use std::cell::RefCell;
56 //! use std::rc::Rc;
57 //!
58 //! fn main() {
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);
64 //! }
65 //! ```
66 //!
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.
70 //!
71 //! ## Implementation details of logically-immutable methods
72 //!
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`.
77 //!
78 //! ```
79 //! # #![allow(dead_code)]
80 //! use std::cell::RefCell;
81 //!
82 //! struct Graph {
83 //! edges: Vec<(i32, i32)>,
84 //! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
85 //! }
86 //!
87 //! impl Graph {
88 //! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
89 //! // Create a new scope to contain the lifetime of the
90 //! // dynamic borrow
91 //! {
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();
96 //! }
97 //!
98 //! let span_tree = self.calc_span_tree();
99 //! *cache = Some(span_tree);
100 //! }
101 //!
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()
108 //! }
109 //! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
110 //! }
111 //! ```
112 //!
113 //! ## Mutating implementations of `Clone`
114 //!
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
119 //! `Cell<T>`.
120 //!
121 //! ```
122 //! use std::cell::Cell;
123 //!
124 //! struct Rc<T> {
125 //! ptr: *mut RcBox<T>
126 //! }
127 //!
128 //! struct RcBox<T> {
129 //! # #[allow(dead_code)]
130 //! value: T,
131 //! refcount: Cell<usize>
132 //! }
133 //!
134 //! impl<T> Clone for Rc<T> {
135 //! fn clone(&self) -> Rc<T> {
136 //! unsafe {
137 //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
138 //! Rc { ptr: self.ptr }
139 //! }
140 //! }
141 //! }
142 //! ```
143 //!
144
145 #![stable(feature = "rust1", since = "1.0.0")]
146
147 use clone::Clone;
148 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
149 use convert::From;
150 use default::Default;
151 use fmt::{self, Debug, Display};
152 use marker::{Copy, PhantomData, Send, Sync, Sized, Unsize};
153 use ops::{Deref, DerefMut, Drop, FnOnce, CoerceUnsized};
154 use option::Option;
155 use option::Option::{None, Some};
156 use result::Result;
157 use result::Result::{Ok, Err};
158
159 /// A mutable memory location that admits only `Copy` data.
160 ///
161 /// See the [module-level documentation](index.html) for more.
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub struct Cell<T> {
164 value: UnsafeCell<T>,
165 }
166
167 impl<T:Copy> Cell<T> {
168 /// Creates a new `Cell` containing the given value.
169 ///
170 /// # Examples
171 ///
172 /// ```
173 /// use std::cell::Cell;
174 ///
175 /// let c = Cell::new(5);
176 /// ```
177 #[stable(feature = "rust1", since = "1.0.0")]
178 #[inline]
179 pub const fn new(value: T) -> Cell<T> {
180 Cell {
181 value: UnsafeCell::new(value),
182 }
183 }
184
185 /// Returns a copy of the contained value.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use std::cell::Cell;
191 ///
192 /// let c = Cell::new(5);
193 ///
194 /// let five = c.get();
195 /// ```
196 #[inline]
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn get(&self) -> T {
199 unsafe{ *self.value.get() }
200 }
201
202 /// Sets the contained value.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use std::cell::Cell;
208 ///
209 /// let c = Cell::new(5);
210 ///
211 /// c.set(10);
212 /// ```
213 #[inline]
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn set(&self, value: T) {
216 unsafe {
217 *self.value.get() = value;
218 }
219 }
220
221 /// Returns a reference to the underlying `UnsafeCell`.
222 ///
223 /// # Examples
224 ///
225 /// ```
226 /// #![feature(as_unsafe_cell)]
227 ///
228 /// use std::cell::Cell;
229 ///
230 /// let c = Cell::new(5);
231 ///
232 /// let uc = c.as_unsafe_cell();
233 /// ```
234 #[inline]
235 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
236 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
237 pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
238 &self.value
239 }
240
241 /// Returns a raw pointer to the underlying data in this cell.
242 ///
243 /// # Examples
244 ///
245 /// ```
246 /// use std::cell::Cell;
247 ///
248 /// let c = Cell::new(5);
249 ///
250 /// let ptr = c.as_ptr();
251 /// ```
252 #[inline]
253 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
254 pub fn as_ptr(&self) -> *mut T {
255 self.value.get()
256 }
257
258 /// Returns a mutable reference to the underlying data.
259 ///
260 /// This call borrows `Cell` mutably (at compile-time) which guarantees
261 /// that we possess the only reference.
262 ///
263 /// # Examples
264 ///
265 /// ```
266 /// use std::cell::Cell;
267 ///
268 /// let mut c = Cell::new(5);
269 /// *c.get_mut() += 1;
270 ///
271 /// assert_eq!(c.get(), 6);
272 /// ```
273 #[inline]
274 #[stable(feature = "cell_get_mut", since = "1.11.0")]
275 pub fn get_mut(&mut self) -> &mut T {
276 unsafe {
277 &mut *self.value.get()
278 }
279 }
280 }
281
282 #[stable(feature = "rust1", since = "1.0.0")]
283 unsafe impl<T> Send for Cell<T> where T: Send {}
284
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T> !Sync for Cell<T> {}
287
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl<T:Copy> Clone for Cell<T> {
290 #[inline]
291 fn clone(&self) -> Cell<T> {
292 Cell::new(self.get())
293 }
294 }
295
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<T:Default + Copy> Default for Cell<T> {
298 #[inline]
299 fn default() -> Cell<T> {
300 Cell::new(Default::default())
301 }
302 }
303
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<T:PartialEq + Copy> PartialEq for Cell<T> {
306 #[inline]
307 fn eq(&self, other: &Cell<T>) -> bool {
308 self.get() == other.get()
309 }
310 }
311
312 #[stable(feature = "cell_eq", since = "1.2.0")]
313 impl<T:Eq + Copy> Eq for Cell<T> {}
314
315 #[stable(feature = "cell_ord", since = "1.10.0")]
316 impl<T:PartialOrd + Copy> PartialOrd for Cell<T> {
317 #[inline]
318 fn partial_cmp(&self, other: &Cell<T>) -> Option<Ordering> {
319 self.get().partial_cmp(&other.get())
320 }
321
322 #[inline]
323 fn lt(&self, other: &Cell<T>) -> bool {
324 self.get() < other.get()
325 }
326
327 #[inline]
328 fn le(&self, other: &Cell<T>) -> bool {
329 self.get() <= other.get()
330 }
331
332 #[inline]
333 fn gt(&self, other: &Cell<T>) -> bool {
334 self.get() > other.get()
335 }
336
337 #[inline]
338 fn ge(&self, other: &Cell<T>) -> bool {
339 self.get() >= other.get()
340 }
341 }
342
343 #[stable(feature = "cell_ord", since = "1.10.0")]
344 impl<T:Ord + Copy> Ord for Cell<T> {
345 #[inline]
346 fn cmp(&self, other: &Cell<T>) -> Ordering {
347 self.get().cmp(&other.get())
348 }
349 }
350
351 #[stable(feature = "cell_from", since = "1.12.0")]
352 impl<T: Copy> From<T> for Cell<T> {
353 fn from(t: T) -> Cell<T> {
354 Cell::new(t)
355 }
356 }
357
358 /// A mutable memory location with dynamically checked borrow rules
359 ///
360 /// See the [module-level documentation](index.html) for more.
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub struct RefCell<T: ?Sized> {
363 borrow: Cell<BorrowFlag>,
364 value: UnsafeCell<T>,
365 }
366
367 /// An enumeration of values returned from the `state` method on a `RefCell<T>`.
368 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
369 #[unstable(feature = "borrow_state", issue = "27733")]
370 pub enum BorrowState {
371 /// The cell is currently being read, there is at least one active `borrow`.
372 Reading,
373 /// The cell is currently being written to, there is an active `borrow_mut`.
374 Writing,
375 /// There are no outstanding borrows on this cell.
376 Unused,
377 }
378
379 /// An error returned by [`RefCell::try_borrow`](struct.RefCell.html#method.try_borrow).
380 #[unstable(feature = "try_borrow", issue = "35070")]
381 pub struct BorrowError<'a, T: 'a + ?Sized> {
382 marker: PhantomData<&'a RefCell<T>>,
383 }
384
385 #[unstable(feature = "try_borrow", issue = "35070")]
386 impl<'a, T: ?Sized> Debug for BorrowError<'a, T> {
387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 f.debug_struct("BorrowError").finish()
389 }
390 }
391
392 #[unstable(feature = "try_borrow", issue = "35070")]
393 impl<'a, T: ?Sized> Display for BorrowError<'a, T> {
394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395 Display::fmt("already mutably borrowed", f)
396 }
397 }
398
399 /// An error returned by [`RefCell::try_borrow_mut`](struct.RefCell.html#method.try_borrow_mut).
400 #[unstable(feature = "try_borrow", issue = "35070")]
401 pub struct BorrowMutError<'a, T: 'a + ?Sized> {
402 marker: PhantomData<&'a RefCell<T>>,
403 }
404
405 #[unstable(feature = "try_borrow", issue = "35070")]
406 impl<'a, T: ?Sized> Debug for BorrowMutError<'a, T> {
407 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
408 f.debug_struct("BorrowMutError").finish()
409 }
410 }
411
412 #[unstable(feature = "try_borrow", issue = "35070")]
413 impl<'a, T: ?Sized> Display for BorrowMutError<'a, T> {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 Display::fmt("already borrowed", f)
416 }
417 }
418
419 // Values [1, MAX-1] represent the number of `Ref` active
420 // (will not outgrow its range since `usize` is the size of the address space)
421 type BorrowFlag = usize;
422 const UNUSED: BorrowFlag = 0;
423 const WRITING: BorrowFlag = !0;
424
425 impl<T> RefCell<T> {
426 /// Creates a new `RefCell` containing `value`.
427 ///
428 /// # Examples
429 ///
430 /// ```
431 /// use std::cell::RefCell;
432 ///
433 /// let c = RefCell::new(5);
434 /// ```
435 #[stable(feature = "rust1", since = "1.0.0")]
436 #[inline]
437 pub const fn new(value: T) -> RefCell<T> {
438 RefCell {
439 value: UnsafeCell::new(value),
440 borrow: Cell::new(UNUSED),
441 }
442 }
443
444 /// Consumes the `RefCell`, returning the wrapped value.
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// use std::cell::RefCell;
450 ///
451 /// let c = RefCell::new(5);
452 ///
453 /// let five = c.into_inner();
454 /// ```
455 #[stable(feature = "rust1", since = "1.0.0")]
456 #[inline]
457 pub fn into_inner(self) -> T {
458 // Since this function takes `self` (the `RefCell`) by value, the
459 // compiler statically verifies that it is not currently borrowed.
460 // Therefore the following assertion is just a `debug_assert!`.
461 debug_assert!(self.borrow.get() == UNUSED);
462 unsafe { self.value.into_inner() }
463 }
464 }
465
466 impl<T: ?Sized> RefCell<T> {
467 /// Query the current state of this `RefCell`
468 ///
469 /// The returned value can be dispatched on to determine if a call to
470 /// `borrow` or `borrow_mut` would succeed.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// #![feature(borrow_state)]
476 ///
477 /// use std::cell::{BorrowState, RefCell};
478 ///
479 /// let c = RefCell::new(5);
480 ///
481 /// match c.borrow_state() {
482 /// BorrowState::Writing => println!("Cannot be borrowed"),
483 /// BorrowState::Reading => println!("Cannot be borrowed mutably"),
484 /// BorrowState::Unused => println!("Can be borrowed (mutably as well)"),
485 /// }
486 /// ```
487 #[unstable(feature = "borrow_state", issue = "27733")]
488 #[inline]
489 pub fn borrow_state(&self) -> BorrowState {
490 match self.borrow.get() {
491 WRITING => BorrowState::Writing,
492 UNUSED => BorrowState::Unused,
493 _ => BorrowState::Reading,
494 }
495 }
496
497 /// Immutably borrows the wrapped value.
498 ///
499 /// The borrow lasts until the returned `Ref` exits scope. Multiple
500 /// immutable borrows can be taken out at the same time.
501 ///
502 /// # Panics
503 ///
504 /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
505 /// [`try_borrow`](#method.try_borrow).
506 ///
507 /// # Examples
508 ///
509 /// ```
510 /// use std::cell::RefCell;
511 ///
512 /// let c = RefCell::new(5);
513 ///
514 /// let borrowed_five = c.borrow();
515 /// let borrowed_five2 = c.borrow();
516 /// ```
517 ///
518 /// An example of panic:
519 ///
520 /// ```
521 /// use std::cell::RefCell;
522 /// use std::thread;
523 ///
524 /// let result = thread::spawn(move || {
525 /// let c = RefCell::new(5);
526 /// let m = c.borrow_mut();
527 ///
528 /// let b = c.borrow(); // this causes a panic
529 /// }).join();
530 ///
531 /// assert!(result.is_err());
532 /// ```
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[inline]
535 pub fn borrow(&self) -> Ref<T> {
536 self.try_borrow().expect("already mutably borrowed")
537 }
538
539 /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
540 /// borrowed.
541 ///
542 /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be
543 /// taken out at the same time.
544 ///
545 /// This is the non-panicking variant of [`borrow`](#method.borrow).
546 ///
547 /// # Examples
548 ///
549 /// ```
550 /// #![feature(try_borrow)]
551 ///
552 /// use std::cell::RefCell;
553 ///
554 /// let c = RefCell::new(5);
555 ///
556 /// {
557 /// let m = c.borrow_mut();
558 /// assert!(c.try_borrow().is_err());
559 /// }
560 ///
561 /// {
562 /// let m = c.borrow();
563 /// assert!(c.try_borrow().is_ok());
564 /// }
565 /// ```
566 #[unstable(feature = "try_borrow", issue = "35070")]
567 #[inline]
568 pub fn try_borrow(&self) -> Result<Ref<T>, BorrowError<T>> {
569 match BorrowRef::new(&self.borrow) {
570 Some(b) => Ok(Ref {
571 value: unsafe { &*self.value.get() },
572 borrow: b,
573 }),
574 None => Err(BorrowError { marker: PhantomData }),
575 }
576 }
577
578 /// Mutably borrows the wrapped value.
579 ///
580 /// The borrow lasts until the returned `RefMut` exits scope. The value
581 /// cannot be borrowed while this borrow is active.
582 ///
583 /// # Panics
584 ///
585 /// Panics if the value is currently borrowed. For a non-panicking variant, use
586 /// [`try_borrow_mut`](#method.try_borrow_mut).
587 ///
588 /// # Examples
589 ///
590 /// ```
591 /// use std::cell::RefCell;
592 ///
593 /// let c = RefCell::new(5);
594 ///
595 /// *c.borrow_mut() = 7;
596 ///
597 /// assert_eq!(*c.borrow(), 7);
598 /// ```
599 ///
600 /// An example of panic:
601 ///
602 /// ```
603 /// use std::cell::RefCell;
604 /// use std::thread;
605 ///
606 /// let result = thread::spawn(move || {
607 /// let c = RefCell::new(5);
608 /// let m = c.borrow();
609 ///
610 /// let b = c.borrow_mut(); // this causes a panic
611 /// }).join();
612 ///
613 /// assert!(result.is_err());
614 /// ```
615 #[stable(feature = "rust1", since = "1.0.0")]
616 #[inline]
617 pub fn borrow_mut(&self) -> RefMut<T> {
618 self.try_borrow_mut().expect("already borrowed")
619 }
620
621 /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
622 ///
623 /// The borrow lasts until the returned `RefMut` exits scope. The value cannot be borrowed
624 /// while this borrow is active.
625 ///
626 /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
627 ///
628 /// # Examples
629 ///
630 /// ```
631 /// #![feature(try_borrow)]
632 ///
633 /// use std::cell::RefCell;
634 ///
635 /// let c = RefCell::new(5);
636 ///
637 /// {
638 /// let m = c.borrow();
639 /// assert!(c.try_borrow_mut().is_err());
640 /// }
641 ///
642 /// assert!(c.try_borrow_mut().is_ok());
643 /// ```
644 #[unstable(feature = "try_borrow", issue = "35070")]
645 #[inline]
646 pub fn try_borrow_mut(&self) -> Result<RefMut<T>, BorrowMutError<T>> {
647 match BorrowRefMut::new(&self.borrow) {
648 Some(b) => Ok(RefMut {
649 value: unsafe { &mut *self.value.get() },
650 borrow: b,
651 }),
652 None => Err(BorrowMutError { marker: PhantomData }),
653 }
654 }
655
656 /// Returns a reference to the underlying `UnsafeCell`.
657 ///
658 /// This can be used to circumvent `RefCell`'s safety checks.
659 ///
660 /// This function is `unsafe` because `UnsafeCell`'s field is public.
661 ///
662 /// # Examples
663 ///
664 /// ```
665 /// #![feature(as_unsafe_cell)]
666 ///
667 /// use std::cell::RefCell;
668 ///
669 /// let c = RefCell::new(5);
670 /// let c = unsafe { c.as_unsafe_cell() };
671 /// ```
672 #[inline]
673 #[unstable(feature = "as_unsafe_cell", issue = "27708")]
674 #[rustc_deprecated(since = "1.12.0", reason = "renamed to as_ptr")]
675 pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
676 &self.value
677 }
678
679 /// Returns a raw pointer to the underlying data in this cell.
680 ///
681 /// # Examples
682 ///
683 /// ```
684 /// use std::cell::RefCell;
685 ///
686 /// let c = RefCell::new(5);
687 ///
688 /// let ptr = c.as_ptr();
689 /// ```
690 #[inline]
691 #[stable(feature = "cell_as_ptr", since = "1.12.0")]
692 pub fn as_ptr(&self) -> *mut T {
693 self.value.get()
694 }
695
696 /// Returns a mutable reference to the underlying data.
697 ///
698 /// This call borrows `RefCell` mutably (at compile-time) so there is no
699 /// need for dynamic checks.
700 ///
701 /// # Examples
702 ///
703 /// ```
704 /// use std::cell::RefCell;
705 ///
706 /// let mut c = RefCell::new(5);
707 /// *c.get_mut() += 1;
708 ///
709 /// assert_eq!(c, RefCell::new(6));
710 /// ```
711 #[inline]
712 #[stable(feature = "cell_get_mut", since = "1.11.0")]
713 pub fn get_mut(&mut self) -> &mut T {
714 unsafe {
715 &mut *self.value.get()
716 }
717 }
718 }
719
720 #[stable(feature = "rust1", since = "1.0.0")]
721 unsafe impl<T: ?Sized> Send for RefCell<T> where T: Send {}
722
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl<T: ?Sized> !Sync for RefCell<T> {}
725
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<T: Clone> Clone for RefCell<T> {
728 #[inline]
729 fn clone(&self) -> RefCell<T> {
730 RefCell::new(self.borrow().clone())
731 }
732 }
733
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<T:Default> Default for RefCell<T> {
736 #[inline]
737 fn default() -> RefCell<T> {
738 RefCell::new(Default::default())
739 }
740 }
741
742 #[stable(feature = "rust1", since = "1.0.0")]
743 impl<T: ?Sized + PartialEq> PartialEq for RefCell<T> {
744 #[inline]
745 fn eq(&self, other: &RefCell<T>) -> bool {
746 *self.borrow() == *other.borrow()
747 }
748 }
749
750 #[stable(feature = "cell_eq", since = "1.2.0")]
751 impl<T: ?Sized + Eq> Eq for RefCell<T> {}
752
753 #[stable(feature = "cell_ord", since = "1.10.0")]
754 impl<T: ?Sized + PartialOrd> PartialOrd for RefCell<T> {
755 #[inline]
756 fn partial_cmp(&self, other: &RefCell<T>) -> Option<Ordering> {
757 self.borrow().partial_cmp(&*other.borrow())
758 }
759
760 #[inline]
761 fn lt(&self, other: &RefCell<T>) -> bool {
762 *self.borrow() < *other.borrow()
763 }
764
765 #[inline]
766 fn le(&self, other: &RefCell<T>) -> bool {
767 *self.borrow() <= *other.borrow()
768 }
769
770 #[inline]
771 fn gt(&self, other: &RefCell<T>) -> bool {
772 *self.borrow() > *other.borrow()
773 }
774
775 #[inline]
776 fn ge(&self, other: &RefCell<T>) -> bool {
777 *self.borrow() >= *other.borrow()
778 }
779 }
780
781 #[stable(feature = "cell_ord", since = "1.10.0")]
782 impl<T: ?Sized + Ord> Ord for RefCell<T> {
783 #[inline]
784 fn cmp(&self, other: &RefCell<T>) -> Ordering {
785 self.borrow().cmp(&*other.borrow())
786 }
787 }
788
789 #[stable(feature = "cell_from", since = "1.12.0")]
790 impl<T> From<T> for RefCell<T> {
791 fn from(t: T) -> RefCell<T> {
792 RefCell::new(t)
793 }
794 }
795
796 struct BorrowRef<'b> {
797 borrow: &'b Cell<BorrowFlag>,
798 }
799
800 impl<'b> BorrowRef<'b> {
801 #[inline]
802 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
803 match borrow.get() {
804 WRITING => None,
805 b => {
806 borrow.set(b + 1);
807 Some(BorrowRef { borrow: borrow })
808 },
809 }
810 }
811 }
812
813 impl<'b> Drop for BorrowRef<'b> {
814 #[inline]
815 fn drop(&mut self) {
816 let borrow = self.borrow.get();
817 debug_assert!(borrow != WRITING && borrow != UNUSED);
818 self.borrow.set(borrow - 1);
819 }
820 }
821
822 impl<'b> Clone for BorrowRef<'b> {
823 #[inline]
824 fn clone(&self) -> BorrowRef<'b> {
825 // Since this Ref exists, we know the borrow flag
826 // is not set to WRITING.
827 let borrow = self.borrow.get();
828 debug_assert!(borrow != UNUSED);
829 // Prevent the borrow counter from overflowing.
830 assert!(borrow != WRITING);
831 self.borrow.set(borrow + 1);
832 BorrowRef { borrow: self.borrow }
833 }
834 }
835
836 /// Wraps a borrowed reference to a value in a `RefCell` box.
837 /// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
838 ///
839 /// See the [module-level documentation](index.html) for more.
840 #[stable(feature = "rust1", since = "1.0.0")]
841 pub struct Ref<'b, T: ?Sized + 'b> {
842 value: &'b T,
843 borrow: BorrowRef<'b>,
844 }
845
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<'b, T: ?Sized> Deref for Ref<'b, T> {
848 type Target = T;
849
850 #[inline]
851 fn deref(&self) -> &T {
852 self.value
853 }
854 }
855
856 impl<'b, T: ?Sized> Ref<'b, T> {
857 /// Copies a `Ref`.
858 ///
859 /// The `RefCell` is already immutably borrowed, so this cannot fail.
860 ///
861 /// This is an associated function that needs to be used as
862 /// `Ref::clone(...)`. A `Clone` implementation or a method would interfere
863 /// with the widespread use of `r.borrow().clone()` to clone the contents of
864 /// a `RefCell`.
865 #[unstable(feature = "cell_extras",
866 reason = "likely to be moved to a method, pending language changes",
867 issue = "27746")]
868 #[inline]
869 pub fn clone(orig: &Ref<'b, T>) -> Ref<'b, T> {
870 Ref {
871 value: orig.value,
872 borrow: orig.borrow.clone(),
873 }
874 }
875
876 /// Make a new `Ref` for a component of the borrowed data.
877 ///
878 /// The `RefCell` is already immutably borrowed, so this cannot fail.
879 ///
880 /// This is an associated function that needs to be used as `Ref::map(...)`.
881 /// A method would interfere with methods of the same name on the contents
882 /// of a `RefCell` used through `Deref`.
883 ///
884 /// # Example
885 ///
886 /// ```
887 /// use std::cell::{RefCell, Ref};
888 ///
889 /// let c = RefCell::new((5, 'b'));
890 /// let b1: Ref<(u32, char)> = c.borrow();
891 /// let b2: Ref<u32> = Ref::map(b1, |t| &t.0);
892 /// assert_eq!(*b2, 5)
893 /// ```
894 #[stable(feature = "cell_map", since = "1.8.0")]
895 #[inline]
896 pub fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, U>
897 where F: FnOnce(&T) -> &U
898 {
899 Ref {
900 value: f(orig.value),
901 borrow: orig.borrow,
902 }
903 }
904 }
905
906 #[unstable(feature = "coerce_unsized", issue = "27732")]
907 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Ref<'b, U>> for Ref<'b, T> {}
908
909 impl<'b, T: ?Sized> RefMut<'b, T> {
910 /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum
911 /// variant.
912 ///
913 /// The `RefCell` is already mutably borrowed, so this cannot fail.
914 ///
915 /// This is an associated function that needs to be used as
916 /// `RefMut::map(...)`. A method would interfere with methods of the same
917 /// name on the contents of a `RefCell` used through `Deref`.
918 ///
919 /// # Example
920 ///
921 /// ```
922 /// use std::cell::{RefCell, RefMut};
923 ///
924 /// let c = RefCell::new((5, 'b'));
925 /// {
926 /// let b1: RefMut<(u32, char)> = c.borrow_mut();
927 /// let mut b2: RefMut<u32> = RefMut::map(b1, |t| &mut t.0);
928 /// assert_eq!(*b2, 5);
929 /// *b2 = 42;
930 /// }
931 /// assert_eq!(*c.borrow(), (42, 'b'));
932 /// ```
933 #[stable(feature = "cell_map", since = "1.8.0")]
934 #[inline]
935 pub fn map<U: ?Sized, F>(orig: RefMut<'b, T>, f: F) -> RefMut<'b, U>
936 where F: FnOnce(&mut T) -> &mut U
937 {
938 RefMut {
939 value: f(orig.value),
940 borrow: orig.borrow,
941 }
942 }
943 }
944
945 struct BorrowRefMut<'b> {
946 borrow: &'b Cell<BorrowFlag>,
947 }
948
949 impl<'b> Drop for BorrowRefMut<'b> {
950 #[inline]
951 fn drop(&mut self) {
952 let borrow = self.borrow.get();
953 debug_assert!(borrow == WRITING);
954 self.borrow.set(UNUSED);
955 }
956 }
957
958 impl<'b> BorrowRefMut<'b> {
959 #[inline]
960 fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
961 match borrow.get() {
962 UNUSED => {
963 borrow.set(WRITING);
964 Some(BorrowRefMut { borrow: borrow })
965 },
966 _ => None,
967 }
968 }
969 }
970
971 /// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
972 ///
973 /// See the [module-level documentation](index.html) for more.
974 #[stable(feature = "rust1", since = "1.0.0")]
975 pub struct RefMut<'b, T: ?Sized + 'b> {
976 value: &'b mut T,
977 borrow: BorrowRefMut<'b>,
978 }
979
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
982 type Target = T;
983
984 #[inline]
985 fn deref(&self) -> &T {
986 self.value
987 }
988 }
989
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
992 #[inline]
993 fn deref_mut(&mut self) -> &mut T {
994 self.value
995 }
996 }
997
998 #[unstable(feature = "coerce_unsized", issue = "27732")]
999 impl<'b, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RefMut<'b, U>> for RefMut<'b, T> {}
1000
1001 /// The core primitive for interior mutability in Rust.
1002 ///
1003 /// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
1004 /// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
1005 /// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
1006 /// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
1007 ///
1008 /// The compiler makes optimizations based on the knowledge that `&T` is not mutably aliased or
1009 /// mutated, and that `&mut T` is unique. When building abstractions like `Cell`, `RefCell`,
1010 /// `Mutex`, etc, you need to turn these optimizations off. `UnsafeCell` is the only legal way
1011 /// to do this. When `UnsafeCell<T>` is immutably aliased, it is still safe to obtain a mutable
1012 /// reference to its interior and/or to mutate it. However, it is up to the abstraction designer
1013 /// to ensure that no two mutable references obtained this way are active at the same time, and
1014 /// that there are no active mutable references or mutations when an immutable reference is obtained
1015 /// from the cell. This is often done via runtime checks.
1016 ///
1017 /// Note that while mutating or mutably aliasing the contents of an `& UnsafeCell<T>` is
1018 /// okay (provided you enforce the invariants some other way); it is still undefined behavior
1019 /// to have multiple `&mut UnsafeCell<T>` aliases.
1020 ///
1021 ///
1022 /// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```
1027 /// use std::cell::UnsafeCell;
1028 /// use std::marker::Sync;
1029 ///
1030 /// # #[allow(dead_code)]
1031 /// struct NotThreadSafe<T> {
1032 /// value: UnsafeCell<T>,
1033 /// }
1034 ///
1035 /// unsafe impl<T> Sync for NotThreadSafe<T> {}
1036 /// ```
1037 #[lang = "unsafe_cell"]
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 pub struct UnsafeCell<T: ?Sized> {
1040 value: T,
1041 }
1042
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<T: ?Sized> !Sync for UnsafeCell<T> {}
1045
1046 impl<T> UnsafeCell<T> {
1047 /// Constructs a new instance of `UnsafeCell` which will wrap the specified
1048 /// value.
1049 ///
1050 /// All access to the inner value through methods is `unsafe`.
1051 ///
1052 /// # Examples
1053 ///
1054 /// ```
1055 /// use std::cell::UnsafeCell;
1056 ///
1057 /// let uc = UnsafeCell::new(5);
1058 /// ```
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 #[inline]
1061 pub const fn new(value: T) -> UnsafeCell<T> {
1062 UnsafeCell { value: value }
1063 }
1064
1065 /// Unwraps the value.
1066 ///
1067 /// # Safety
1068 ///
1069 /// This function is unsafe because this thread or another thread may currently be
1070 /// inspecting the inner value.
1071 ///
1072 /// # Examples
1073 ///
1074 /// ```
1075 /// use std::cell::UnsafeCell;
1076 ///
1077 /// let uc = UnsafeCell::new(5);
1078 ///
1079 /// let five = unsafe { uc.into_inner() };
1080 /// ```
1081 #[inline]
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub unsafe fn into_inner(self) -> T {
1084 self.value
1085 }
1086 }
1087
1088 impl<T: ?Sized> UnsafeCell<T> {
1089 /// Gets a mutable pointer to the wrapped value.
1090 ///
1091 /// This can be cast to a pointer of any kind.
1092 /// Ensure that the access is unique when casting to
1093 /// `&mut T`, and ensure that there are no mutations or mutable
1094 /// aliases going on when casting to `&T`
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```
1099 /// use std::cell::UnsafeCell;
1100 ///
1101 /// let uc = UnsafeCell::new(5);
1102 ///
1103 /// let five = uc.get();
1104 /// ```
1105 #[inline]
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub fn get(&self) -> *mut T {
1108 &self.value as *const T as *mut T
1109 }
1110 }
1111
1112 #[stable(feature = "unsafe_cell_default", since = "1.9.0")]
1113 impl<T: Default> Default for UnsafeCell<T> {
1114 fn default() -> UnsafeCell<T> {
1115 UnsafeCell::new(Default::default())
1116 }
1117 }
1118
1119 #[stable(feature = "cell_from", since = "1.12.0")]
1120 impl<T> From<T> for UnsafeCell<T> {
1121 fn from(t: T) -> UnsafeCell<T> {
1122 UnsafeCell::new(t)
1123 }
1124 }