Skip to content

In 2930-read-buf, correct the section on using the Read trait with an uninitialized buffer #3929

@Jason5Lee

Description

@Jason5Lee

In the current 2930-read-buf, it says:

let mut buf: [u8; 1024] = unsafe { MaybeUninit::uninit().assume_init() };
let nread = reader.read(&mut buf)?;
process_data(&buf[..nread]);

However, whether it is allowed to call assume_init() on an array of uninitialized integers is
still subject of discussion.

That “still subject of discussion” issue—about the validity of integers and floating point—has been closed, with the conclusion that uninitialized integers are not valid.

After further research I found a discussion about whether &mut uninit should be UB. That issue is still open and unresolved. If I understand the rationale correctly, and if &mut uninit is not immediately UB as the discussion suggests, then the following code would not be UB provided the reader is well-behaved:

let mut buf: MaybeUninit<[u8; 1024]> = MaybeUninit::uninit();
let but_mut = unsafe { std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, 1024) };
let nread = reader.read(&mut buf)?;
process_data(&buf[..nread]);

I think the code sample and accompanying description should be updated to reflect this change and to clarify which aspects are actually still under discussion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions