Mismatch between spec and implementation of DataInputStream.readFully(byte[], int, int)

Johannes Kuhn info at j-kuhn.de
Thu May 14 14:24:45 UTC 2020


Found a small mismatch between the specification of 
DataInputStream.readFully(byte[] b, int off, int len) and its 
implementation.

In particular, it doesn't throw an IndexOutOfBoundsException if offset 
is negative and len is 0.

Reproducer below.

I suggest changing the specification of this method to allow that behavior.
This change should also affect DataInput, where care has to be taken 
that both behaviors are legal.

- Johannes

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class DISBug {
     public static void main(String[] args) throws IOException {
         try (var bais = new ByteArrayInputStream(new byte[0]);
                 var dis = new DataInputStream(bais)) {
             // From the spec:
             // throws IndexOutOfBoundsException - if off is negative, 
len is negative, or len is greater than b.length - off.
             byte[] b = new byte[0];
             int off = -1; // This is not valid
             int len = 0;
             dis.readFully(b, off, len);
             throw new AssertionError("readFully did not throw");
         } catch (IndexOutOfBoundsException expected) {
             // Ignore, this exception is expected
         }
     }
}



More information about the core-libs-dev mailing list