splix / polkaj

Library to access and build for Polkadot using Java
Apache License 2.0
61 stars 54 forks source link

The uint32 writer implementation of SCALE has problem #81

Open LBruyne opened 2 years ago

LBruyne commented 2 years ago

write method of UInt32Writer should has a param of type Long, not integer. The current version will have a problem when encoding uint32 like 2282200012 (which is beyond the limit of integer).

LBruyne commented 2 years ago

the implementation can be:

public class UInt32Writer implements ScaleWriter<Long> {

    private static final long MAX_UINT32 = Long.parseLong("4294967295");

    @Override
    public void write(ScaleCodecWriter wrt, Long value) throws IOException {
        if (value < 0 || value > MAX_UINT32) {
            throw new IllegalArgumentException("Only values in range 0.." + MAX_UINT32 + " are supported: " + value);
        }
        for( int i = 0; i < 4; i++) {
            wrt.directWrite(Math.toIntExact((value >> (i * 8)) & 0xff));
        }
    }
}