Description
In a recent URLO post, someone saw the "no guarantees" paragraph in read_exact
, and this convinced them not to use it (and to instead use read
).
The post: (link)
Okay. That does means I should replace all read with read_exact? Since it said no guarantee I was hesitant to use it.
The paragraph:
No guarantees are provided about the contents of buf when this function is called, implementations cannot rely on any property of the contents of buf being true. It is recommended that implementations only write data to buf instead of reading its contents.
While the caution is (or at least was) legitimate, I think for today's rust it's a bit negative. And if this is a user's first real read
method they use, then I can 100% understand getting thrown off by this language.
I'd like to think we can reduce the caution necessary when using it, while still keeping the caution for implementors. Thoughts on replacing it with a more positive message, like the following?
This function may be called with any
buf
, and makes no requirements on the contents ofbuf
or any property about the contents ofbuf
being true. It is recommended that implementations only write data to buf instead of reading its contents.
The italicized "implementations" is taken from the documentation on read
, which reads:
No guarantees are provided about the contents of
buf
when this function is called, implementations cannot rely on any property of the contents ofbuf
being true. It is recommended that implementations only write data tobuf
instead of reading its contents.
I don't think it's necessary to modify the paragraph on read
, as it has much more overall content, as it also contains this following paragraph:
Correspondingly, however, callers of this method may not assume any guarantees about how the implementation uses
buf
. The trait is safe to implement, so it is possible that the code that's supposed to write to the buffer might also read from it. It is your responsibility to make sure thatbuf
is initialized before calling read. Calling read with an uninitializedbuf
(of the kind one obtains viaMaybeUninit<T>
) is not safe, and can lead to undefined behavior.
In addition, the read
documentation is big enough that users can skip over the "no guarantees" paragraph. Case in point, the user from the URLO thread above chose to use read
, while avoiding read_exact
, even though read
contains the exact same paragraph.
I'll end by saying I don't know the full history, but I think this might have had something to do with passing uninitialized byte buffers to read methods. I believe that it's been decided that passing in an uninitialized buffer is UB, though, so it shouldn't be as big of a concern. The current discussion of reading into uninitialized buffers is at 42788.
This issue has been assigned to @poliorcetics via this comment.