|
119 | 119 | //! `Cell<T>`.
|
120 | 120 | //!
|
121 | 121 | //! ```
|
| 122 | +//! #![feature(core_intrinsics)] |
| 123 | +//! #![feature(shared)] |
122 | 124 | //! use std::cell::Cell;
|
| 125 | +//! use std::ptr::Shared; |
| 126 | +//! use std::intrinsics::abort; |
| 127 | +//! use std::intrinsics::assume; |
123 | 128 | //!
|
124 |
| -//! struct Rc<T> { |
125 |
| -//! ptr: *mut RcBox<T> |
| 129 | +//! struct Rc<T: ?Sized> { |
| 130 | +//! ptr: Shared<RcBox<T>> |
126 | 131 | //! }
|
127 | 132 | //!
|
128 |
| -//! struct RcBox<T> { |
129 |
| -//! # #[allow(dead_code)] |
| 133 | +//! struct RcBox<T: ?Sized> { |
| 134 | +//! strong: Cell<usize>, |
| 135 | +//! refcount: Cell<usize>, |
130 | 136 | //! value: T,
|
131 |
| -//! refcount: Cell<usize> |
132 | 137 | //! }
|
133 | 138 | //!
|
134 |
| -//! impl<T> Clone for Rc<T> { |
| 139 | +//! impl<T: ?Sized> Clone for Rc<T> { |
135 | 140 | //! fn clone(&self) -> Rc<T> {
|
136 |
| -//! unsafe { |
137 |
| -//! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); |
138 |
| -//! Rc { ptr: self.ptr } |
139 |
| -//! } |
| 141 | +//! self.inc_strong(); |
| 142 | +//! Rc { ptr: self.ptr } |
| 143 | +//! } |
| 144 | +//! } |
| 145 | +//! |
| 146 | +//! trait RcBoxPtr<T: ?Sized> { |
| 147 | +//! |
| 148 | +//! fn inner(&self) -> &RcBox<T>; |
| 149 | +//! |
| 150 | +//! fn strong(&self) -> usize { |
| 151 | +//! self.inner().strong.get() |
| 152 | +//! } |
| 153 | +//! |
| 154 | +//! fn inc_strong(&self) { |
| 155 | +//! self.inner() |
| 156 | +//! .strong |
| 157 | +//! .set(self.strong() |
| 158 | +//! .checked_add(1) |
| 159 | +//! .unwrap_or_else(|| unsafe { abort() })); |
140 | 160 | //! }
|
141 | 161 | //! }
|
| 162 | +//! |
| 163 | +//! impl<T: ?Sized> RcBoxPtr<T> for Rc<T> { |
| 164 | +//! fn inner(&self) -> &RcBox<T> { |
| 165 | +//! unsafe { |
| 166 | +//! assume(!(*(&self.ptr as *const _ as *const *const ())).is_null()); |
| 167 | +//! &(**self.ptr) |
| 168 | +//! } |
| 169 | +//! } |
| 170 | +//! } |
142 | 171 | //! ```
|
143 | 172 | //!
|
144 | 173 |
|
|
0 commit comments