Allow null as valid param to Int/UInt (#5458)

This commit is contained in:
Jaco
2023-01-29 09:17:21 +02:00
committed by GitHub
parent 680ae0222a
commit c168615305
22 changed files with 186 additions and 168 deletions
+4 -2
View File
@@ -29,7 +29,7 @@ function toPercentage (value: BN, divisor: BN): string {
}
/** @internal */
function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array> | Record<string, string> | ToBn, isNegative: boolean): string | number {
function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array> | Record<string, string> | ToBn | null, isNegative: boolean): string | number {
if (isNumber(value)) {
if (!Number.isInteger(value) || value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER) {
throw new Error('Number needs to be an integer <= Number.MAX_SAFE_INTEGER, i.e. 2 ^ 53 - 1');
@@ -63,6 +63,8 @@ function decodeAbstractInt (value: Exclude<AnyNumber, Uint8Array> | Record<strin
}
return decodeAbstractInt(value[keys[0]], isNegative);
} else if (!value) {
return 0;
}
throw new Error(`Unable to create BN from unknown type ${typeof value}`);
@@ -84,7 +86,7 @@ export abstract class AbstractInt extends BN implements INumber {
readonly #bitLength: UIntBitLength;
constructor (registry: Registry, value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) {
constructor (registry: Registry, value: AnyNumber | null = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isSigned = false) {
// Construct via a string/number, which will be passed in the BN constructor.
// It would be ideal to actually return a BN, but there is an issue:
// https://github.com/indutny/bn.js/issues/206
@@ -63,6 +63,15 @@ describe('Int', (): void => {
).toEqual(-123);
});
it('allows null/undefined', (): void => {
expect(
new Int(registry).toNumber()
).toEqual(0);
expect(
new Int(registry, null).toNumber()
).toEqual(0);
});
it('has a sane inspect', (): void => {
expect(
new Int(registry, '0x12', 16).inspect()
+2 -2
View File
@@ -16,13 +16,13 @@ import { AbstractInt } from '../abstract/Int';
* @noInheritDoc
*/
export class Int extends AbstractInt {
constructor (registry: Registry, value: AnyNumber = 0, bitLength?: UIntBitLength) {
constructor (registry: Registry, value: AnyNumber | null = 0, bitLength?: UIntBitLength) {
super(registry, value, bitLength, true);
}
public static with (bitLength: UIntBitLength, typeName?: string): CodecClass<Int> {
return class extends Int {
constructor (registry: Registry, value?: AnyNumber) {
constructor (registry: Registry, value?: AnyNumber | null) {
super(registry, value, bitLength);
}
+1 -1
View File
@@ -18,7 +18,7 @@ import { AbstractInt } from '../abstract/Int';
export class UInt extends AbstractInt {
public static with (bitLength: UIntBitLength, typeName?: string): CodecClass<UInt> {
return class extends UInt {
constructor (registry: Registry, value?: AnyNumber) {
constructor (registry: Registry, value?: AnyNumber | null) {
super(registry, value, bitLength);
}