Minimum number of bytes for compact encoding (#285)

* Minimum number of bytes for compact encoding

* Cleanup comment
This commit is contained in:
Jaco Greeff
2018-12-25 13:29:33 +01:00
committed by GitHub
parent 212c22abed
commit 7b9ca4ad6e
2 changed files with 12 additions and 10 deletions
+1 -1
View File
@@ -58,7 +58,7 @@ describe('encode', () => {
it('encodes a large value', () => {
expect(
compactToU8a(
new BN('5af3107a4000', 16)
new BN('00005af3107a4000', 16)
)
).toEqual(
new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a])
+11 -9
View File
@@ -35,19 +35,21 @@ export default function compactToU8a (_value: BN | number): Uint8Array {
return bnToU8a(value.shln(2).addn(0b10), 32, true);
}
// Number of bytes needed to represent `value`
const bytesNeeded = Math.ceil(value.bitLength() / 8);
const u8a = bnToU8a(value);
let length = u8a.length;
assert(bytesNeeded >= 4, 'Previous tests match anyting less than 2^30; qed');
// adjust to the minimum number of bytes
while (u8a[length - 1] === 0) {
length--;
}
assert(length >= 4, 'Previous tests match anyting less than 2^30; qed');
return u8aConcat(
new Uint8Array([
new BN(bytesNeeded)
.subn(4) // how many bytes more than 4 do we need?
.shln(2) // clear low
.addn(0b11) // add flag
.toNumber()
// substract 4 as minimum (also catered for in decoding)
((length - 4) << 2) + 0b11
]),
bnToU8a(value)
u8a.subarray(0, length)
);
}