@@ -143,12 +143,76 @@ library as a replacement.
143
143
Add the aforementioned ` MaybeUninit ` type to the standard library:
144
144
145
145
``` rust
146
+ #[repr(transparent)]
146
147
union MaybeUninit <T > {
147
148
uninit : (),
148
149
value : T ,
149
150
}
150
151
```
151
152
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
+
152
216
Deprecate ` uninitialized ` with a deprecation messages that points people to the
153
217
` MaybeUninit ` type. Make calling ` uninitialized ` on an empty type trigger a
154
218
runtime panic which also prints the deprecation message.
0 commit comments