rspec/rules/S4517/java/rule.adoc

48 lines
1.3 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
@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)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]