Skip to content

TypedArrays should support more than Double values #10

@niloc132

Description

@niloc132

From what I can tell in the integer_entities.txt update, the build now can generate int or Integer in some cases instead of Double. This doesn't seem to have been applied to the TypedArray subtypes, resulting in some unique getAt and setAt calls. Working from PlayN sources as I patch them to use elemental2 instead of JSOs, ByteBuffer.getShort now must look like this:

    public final short getShort (int baseOffset) {
      short bytes = 0;
      if (order == ByteOrder.BIG_ENDIAN) {
          bytes = (short)(((byte) (double) byteArray.getAt(baseOffset)) << 8);
          bytes |= (((byte) (double) byteArray.getAt(baseOffset + 1)) & 0xFF);
      } else {
          bytes = (short) (((byte) (double) byteArray.getAt(baseOffset + 1)) << 8);
          bytes |= (((byte) (double) byteArray.getAt(baseOffset)) & 0xFF);
      }
      return bytes;
    }

Since Int8Array is a TypedArray is a JsArrayLike<Double>, the getAt call returns Double, which cannot be shifted, so first we cast to double, which still can't be shifted, so cast to byte. Technically we could cast to int in the second one, but I wanted to be precise here. We of course have to assume that the browser would never return something outside the range of a byte here.

    public final ByteBuffer putInt (int baseOffset, int value) {
      if (order == ByteOrder.BIG_ENDIAN) {
          for (int i = 3; i >= 0; i--) {
              byteArray.setAt(baseOffset + i, (double)(byte)(value & 0xFF));
              value = value >> 8;
          }
      } else {
          for (int i = 0; i <= 3; i++) {
              byteArray.setAt(baseOffset + i, (double)(byte)(value & 0xFF));
              value = value >> 8;
          }
      }
      return this;
    }

Same idea here - the int value is being shifted and masked, and can't be used directly as a double. Granted, the cast to byte isn't technically required here, but it does seem less un-clear to a reader than casting an int to a double so you can put it in a byte array.

I'm not sure exactly how this can be improved, without just listing all of these signatures by hand, but this is pretty terrible Java to have to write. At least in the case of PlayN it is hidden behind emul code, but I had understood that elemental2 was meant to be user facing for the most part.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions