Don't modiy original value on encoding (#958)

This commit is contained in:
Jaco
2021-04-22 14:39:39 +02:00
committed by GitHub
parent 393334409f
commit afd8a9610f
3 changed files with 17 additions and 2 deletions
@@ -47,4 +47,12 @@ describe('compactFromU8a', (): void => {
)
).toEqual([7, new BN('5af3107a4000', 16)]);
});
it('decodes an actual value', (): void => {
expect(
compactFromU8a(
hexToU8a('0x0284d717')
)[1].toString()
).toEqual('100000000');
});
});
+7
View File
@@ -72,6 +72,13 @@ describe('encode', (): void => {
);
});
it('does not modify the original', (): void => {
const original = new BN(123456);
expect(compactToU8a(original)).toEqual(new Uint8Array([2, 137, 7, 0]));
expect(original.toString()).toEqual('123456');
});
describe('from Rust', (): void => {
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs
const testCases = [
+2 -2
View File
@@ -29,9 +29,9 @@ export function compactToU8a (_value: BN | BigInt | number): Uint8Array {
if (value.lte(MAX_U8)) {
return new Uint8Array([value.toNumber() << 2]);
} else if (value.lte(MAX_U16)) {
return bnToU8a(value.ishln(2).iadd(BN_ONE), 16, true);
return bnToU8a(value.shln(2).iadd(BN_ONE), 16, true);
} else if (value.lte(MAX_U32)) {
return bnToU8a(value.ishln(2).iadd(BN_TWO), 32, true);
return bnToU8a(value.shln(2).iadd(BN_TWO), 32, true);
}
const u8a = bnToU8a(value);