Skip to content

Commit b4a4734

Browse files
committed
Add details about MaybeUninit API
1 parent 5f6c6cd commit b4a4734

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

text/0000-uninitialized-uninhabited.md

+64
Original file line numberDiff line numberDiff line change
@@ -143,12 +143,76 @@ library as a replacement.
143143
Add the aforementioned `MaybeUninit` type to the standard library:
144144

145145
```rust
146+
#[repr(transparent)]
146147
union MaybeUninit<T> {
147148
uninit: (),
148149
value: T,
149150
}
150151
```
151152

153+
The type should have at least the following interface
154+
155+
```rust
156+
impl<T> MaybeUninit<T> {
157+
/// Create a new `MaybeUninit` in an uninitialized state.
158+
pub fn uninitialized() -> MaybeUninit<T> {
159+
MaybeUninit {
160+
uninit: (),
161+
}
162+
}
163+
164+
/// Set the value of the `MaybeUninit`. The overwrites any previous value without dropping it.
165+
pub fn set(&mut self, val: T) -> &mut T {
166+
unsafe {
167+
self.value = val;
168+
&mut self.value
169+
}
170+
}
171+
172+
/// Take the value of the `MaybeUninit`, putting it into an uninitialized state.
173+
///
174+
/// # Unsafety
175+
///
176+
/// It is up to the caller to guarantee that the the `MaybeUninit` really is in an initialized
177+
/// state, otherwise undefined behaviour will result.
178+
pub unsafe fn get(&self) -> T {
179+
std::ptr::read(&self.value)
180+
}
181+
182+
/// Get a reference to the contained value.
183+
///
184+
/// # Unsafety
185+
///
186+
/// It is up to the caller to guarantee that the the `MaybeUninit` really is in an initialized
187+
/// state, otherwise undefined behaviour will result.
188+
pub unsafe fn get_ref(&self) -> &T {
189+
&self.value
190+
}
191+
192+
/// Get a mutable reference to the contained value.
193+
///
194+
/// # Unsafety
195+
///
196+
/// It is up to the caller to guarantee that the the `MaybeUninit` really is in an initialized
197+
/// state, otherwise undefined behaviour will result.
198+
pub unsafe fn get_mut(&mut self) -> &mut T {
199+
&mut self.value
200+
}
201+
202+
/// Get a pointer to the contained value. This pointer will only be valid if the `MaybeUninit`
203+
/// is in an initialized state.
204+
pub fn as_ptr(&self) -> *const T {
205+
unsafe { &self.value as *const T }
206+
}
207+
208+
/// Get a mutable pointer to the contained value. This pointer will only be valid if the
209+
/// `MaybeUninit` is in an initialized state.
210+
pub fn as_mut_ptr(&mut self) -> *mut T {
211+
unsafe { &mut self.value as *mut T }
212+
}
213+
}
214+
```
215+
152216
Deprecate `uninitialized` with a deprecation messages that points people to the
153217
`MaybeUninit` type. Make calling `uninitialized` on an empty type trigger a
154218
runtime panic which also prints the deprecation message.

0 commit comments

Comments
 (0)