-
Notifications
You must be signed in to change notification settings - Fork 5.4k
[Analyzer Proposal]: Analyzer/fixer for converting Stream.Read calls to ReadAtLeast and ReadExactly #69159
Description
With the addition of the new Stream ReadAtLeast and ReadExactly methods, there is a pattern of mistakes we can catch with an analyzer and suggest the caller use the new APIs. For example:
stream.Read(buffer, 0, buffer.Length);where the return value isn't checked, and recommend it be changed to a call to ReadExactly.
Or cases where the return value is checked but required to be the same as what was requested:
if (stream.Read(buffer, 0, buffer.Length) != buffer.Length) throw ...;and similarly suggest it use ReadExactly.
If the caller is using a length that is different than the length of the buffer being passed in, and not checking the return value, we can suggest to use ReadAtLeast:
stream.Read(buffer, 0, count);would become:
stream.ReadAtLeast(buffer, count);However, note in the ReadAtLeast case, the caller should still be checking the return value because the ReadAtLeast call could be returning more than count bytes, and this data would be missed if the caller only consumed count bytes from buffer.
One problem with this analyzer might be when we implement #34098. If the caller saw the "Do not discard results of methods marked as DoNotIgnoreReturnValue" warning first and addressed it, they would lose out on this fixer.
cc @stephentoub