Output BitVec toHuman to LSB (limit support) (#4676)

This commit is contained in:
Jaco
2022-03-22 09:41:17 +02:00
committed by GitHub
parent 798e5fcc78
commit 9399c8d24f
4 changed files with 55 additions and 17 deletions
@@ -11,24 +11,41 @@ const TESTS = ['0x00', '0x0817', '0x0837', '0x087b', '0x0c33'];
const registry = new TypeRegistry();
describe('BitVec', (): void => {
TESTS.forEach((test): void => {
describe(test, (): void => {
const input = hexToU8a(test);
describe('decoding known', (): void => {
TESTS.forEach((test): void => {
describe(test, (): void => {
const input = hexToU8a(test);
const bitvec = new BitVec(registry, input);
it('has the right encodedLength', (): void => {
expect(
new BitVec(registry, input).encodedLength
).toEqual((test.length - 2) / 2);
});
it('has the right encodedLength', (): void => {
expect(
bitvec.encodedLength
).toEqual((test.length - 2) / 2);
});
it('re-encodes to the same input value', (): void => {
expect(
new BitVec(registry, input).toU8a()
).toEqual(input);
it('re-encodes to the same input value', (): void => {
expect(
bitvec.toU8a()
).toEqual(input);
});
});
});
});
describe('toHuman() ordering', (): void => {
it('defaults to Lsb', (): void => {
expect(
new BitVec(registry, '0x0100010500').toHuman()
).toEqual('0b10000000_00000000_10000000_10100000_00000000');
});
it('can output to Msb', (): void => {
expect(
new BitVec(registry, '0x0100010500', true).toHuman()
).toEqual('0b00000001_00000000_00000001_00000101_00000000');
});
});
it('has a sane inspect', (): void => {
expect(
new BitVec(registry, '0x0837').inspect()
+12 -2
View File
@@ -41,13 +41,18 @@ function decodeBitVec (value?: AnyU8a): [number, Uint8Array] {
*/
export class BitVec extends Raw {
readonly #decodedLength: number;
readonly #isMsb?: boolean;
constructor (registry: Registry, value?: AnyU8a) {
// In lieu of having the Msb/Lsb identifiers passed through, we default to assuming
// we are dealing with Lsb, which is the default (as of writing) BitVec format used
// in the Polkadot code (this only affects the toHuman displays)
constructor (registry: Registry, value?: AnyU8a, isMsb = false) {
const [decodedLength, u8a] = decodeBitVec(value);
super(registry, u8a);
this.#decodedLength = decodedLength;
this.#isMsb = isMsb;
}
/**
@@ -67,7 +72,12 @@ export class BitVec extends Raw {
}
public override toHuman (): string {
return `0b${[...this.toU8a(true)].map((d) => `00000000${d.toString(2)}`.slice(-8)).join('_')}`;
return `0b${
[...this.toU8a(true)]
.map((d) => `00000000${d.toString(2)}`.slice(-8))
.map((s) => this.#isMsb ? s : s.split('').reverse().join(''))
.join('_')
}`;
}
/**