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