capnproto-java icon indicating copy to clipboard operation
capnproto-java copied to clipboard

Unsigned types are not generated correct

Open anxtfux opened this issue 10 years ago • 5 comments

Since Java does not have unsigned primitive types the generated type for UInt8, UInt16, UInt32 must be short, int, long instead of byte, short, int. For UInt64 is no real solution available but here is the impact not as big as for the smaller types.

// Current UInt8
     public final byte getM0() {
        return _getByteField(0);
      }
      public final void setM0(byte value) {
        _setByteField(0, value);
      }
// Expected UInt8
     public final short getM0() {
        return _getByteField(0) & 0xFF;
      }
      public final void setM0(short value) {
        _setByteField(0, (byte) value);
      }
// Current UInt16
      public final short getM1() {
        return _getShortField(1);
      }
      public final void setM1(short value) {
        _setShortField(1, value);
      }
// Expected UInt16
      public final int getM1() {
        return _getShortField(1) & 0xFFFF;
      }
      public final void setM1(int value) {
        _setShortField(1, (short) value);
      }
// Current UInt32
      public final int getM2() {
        return _getIntField(2);
      }
      public final void setM2(int value) {
        _setIntField(2, value);
      }
// Expected UInt32
      public final long getM2() {
        return _getIntField(2) & 0xFFFF_FFFFL;
      }
      public final void setM2(long value) {
        _setIntField(2, (int) value);
      }


anxtfux avatar Feb 28 '15 15:02 anxtfux

Hm. I feel like representing an unsigned 32-bit integer as an int is a much more faithful representation than shoving it into a 64-bit long, and I don't like the idea of silently truncating bits in the setter methods. I don't think it's too much of a burden to ask that you do the conversions yourself if needed, especially now that Java 8 has methods like Integer.toUnsignedLong(int x) and Integer.compareUnsigned(int x, int y).

Maybe we just need better documentation for the current behavior?

dwrensha avatar Feb 28 '15 17:02 dwrensha

With the current implementation the unsigned types have no meaning in Java. It's a nasty pitfall if you get negative values where it should be impossible only by missing to do the conversion yourself. I think it is very common to express unsigned values with the next higher type, especially for UInt8 and UInt16.

anxtfux avatar Feb 28 '15 19:02 anxtfux

Hey guys, is there any update on this? What is the right way of using uint16 in java? How to use short?

digitwolf avatar May 18 '21 02:05 digitwolf