
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
54 lines
1.4 KiB
Plaintext
54 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
According to the Java documentation, any implementation of the ``++InputSteam.read()++`` method is supposed to read the next byte of data from the input stream. The value byte must be an ``++int++`` in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned.
|
|
|
|
|
|
But in Java, the ``++byte++`` primitive data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127. So by contract, the implementation of an ``++InputSteam.read()++`` method should never directly return a ``++byte++`` primitive data type. A conversion into an unsigned byte must be done before by applying a bitmask.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
@Override
|
|
public int read() throws IOException {
|
|
if (pos == buffer.length()) {
|
|
return -1;
|
|
}
|
|
return buffer.getByte(pos++); // Noncompliant, a signed byte value is returned
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
@Override
|
|
public int read() throws IOException {
|
|
if (pos == buffer.length()) {
|
|
return -1;
|
|
}
|
|
return buffer.getByte(pos++) & 0xFF; // The 0xFF bitmask is applied
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Convert this signed byte into an unsigned byte.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
* Primary location: the argument of the return statement
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|