Skip to content

Commit 639c4f7

Browse files
SimonSapinCentril
authored andcommitted
MaybeUninit::uninit_array docs: better example
1 parent 05c14bc commit 639c4f7

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

src/libcore/mem/maybe_uninit.rs

+20-14
Original file line numberDiff line numberDiff line change
@@ -260,26 +260,32 @@ impl<T> MaybeUninit<T> {
260260

261261
/// Create a new array of `MaybeUninit<T>` items, in an uninitialized state.
262262
///
263+
/// Note: in a future Rust version this method may become unnecessary
264+
/// when array literal syntax allows
265+
/// [repeating const expressions](https://github.com/rust-lang/rust/issues/49147).
266+
/// The example below could then use `let mut buf = [MaybeUninit::<u8>::uninit(); 32];`.
267+
///
263268
/// # Examples
264269
///
265-
/// ```
270+
/// ```no_run
266271
/// #![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice_assume_init)]
272+
///
267273
/// use std::mem::MaybeUninit;
268274
///
269-
/// let input = b"Foo";
270-
/// let f = u8::to_ascii_uppercase;
271-
///
272-
/// let mut buffer: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
273-
/// let vec;
274-
/// let output = if let Some(buffer) = buffer.get_mut(..input.len()) {
275-
/// buffer.iter_mut().zip(input).for_each(|(a, b)| { a.write(f(b)); });
276-
/// unsafe { MaybeUninit::slice_get_ref(buffer) }
277-
/// } else {
278-
/// vec = input.iter().map(f).collect::<Vec<u8>>();
279-
/// &vec
280-
/// };
275+
/// extern "C" {
276+
/// fn read_into_buffer(ptr: *mut u8, max_len: usize) -> usize;
277+
/// }
278+
///
279+
/// /// Returns a (possibly smaller) slice of data that was actually read
280+
/// fn read(buf: &mut [MaybeUninit<u8>]) -> &[u8] {
281+
/// unsafe {
282+
/// let len = read_into_buffer(buf.as_mut_ptr() as *mut u8, buf.len());
283+
/// MaybeUninit::slice_get_ref(&buf[..len])
284+
/// }
285+
/// }
281286
///
282-
/// assert_eq!(output, b"FOO");
287+
/// let mut buf: [MaybeUninit<u8>; 32] = MaybeUninit::uninit_array();
288+
/// let data = read(&mut buf);
283289
/// ```
284290
#[unstable(feature = "maybe_uninit_uninit_array", issue = "0")]
285291
#[inline(always)]

0 commit comments

Comments
 (0)