The result of read() is cast to char or byte before the end of input is checked

tx0/java:unchecked-read-castdefaultwarningbug

What it finds

(char) reader.read() and (byte) in.read() convert the result before it can be compared with -1, the value that means the end of the input. After the cast, the end reads as the character ￿ or the byte -1, which is also a valid byte, so a loop either never ends or stops in the middle of the data.

Reported are casts to char or byte applied directly to a read() without arguments.

From the rule's source, unchecked_read_cast.rs.

Example from the rule's tests
import java.io.IOException;import java.io.Reader; class Chars {  void copy(Reader reader, StringBuilder out) throws IOException {    char c = (char) reader.read();tx0 reports: reader.read() is cast to char before it is compared with -1    int next = reader.read();    if (next != -1) {      out.append((char) next);    }    out.append(c);  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:unchecked-read-cast" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:unchecked-read-cast] reason="..."

tx0 explain tx0/java:unchecked-read-cast shows the same in the terminal. Found a false positive? Report it.