Range as primitive (#3874)

* Range as primitive

* Result/Range

* INumber as Range inner

* Update

* .with on Range

* Basic range decoding

* With

* RangeName

* TypeDefInfo for Range
This commit is contained in:
Jaco
2021-08-14 09:14:53 +02:00
committed by GitHub
parent 9b0d260b33
commit ca17955d83
14 changed files with 83 additions and 122 deletions
+1
View File
@@ -189,6 +189,7 @@ const encoders: Record<TypeDefInfo, (registry: Registry, definitions: Record<str
[TypeDefInfo.Null]: errorUnhandled,
[TypeDefInfo.Option]: tsOption,
[TypeDefInfo.Plain]: tsPlain,
[TypeDefInfo.Range]: errorUnhandled,
[TypeDefInfo.Result]: tsResult,
[TypeDefInfo.Set]: tsSet,
[TypeDefInfo.Si]: tsSi,
+3
View File
@@ -129,6 +129,9 @@ const formatters: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef, def
return typeDef.type;
},
[TypeDefInfo.Range]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
throw new Error(`TypeDefInfo.Range: Not implemented on ${stringify(typeDef)}`);
},
[TypeDefInfo.Set]: (registry: Registry, typeDef: TypeDef, definitions: Record<string, ModuleTypes>, imports: TypeImports, withShortcut: boolean) => {
throw new Error(`TypeDefInfo.Set: Not implemented on ${stringify(typeDef)}`);
},
+4 -6
View File
@@ -7,21 +7,19 @@ import { Range } from '.';
describe('Range', (): void => {
const registry = new TypeRegistry();
const Type = Range.with([U32, U32]);
let range: Range<U32>;
beforeEach((): void => {
range = new Range(
const Clazz = Range.with(U32);
range = new Clazz(
registry,
U32,
[new U32(registry, 1), new U32(registry, 2)]
);
});
it('decodes', (): void => {
const rslt = new Type(registry, new Uint8Array([1, 0, 0, 0, 2, 0, 0, 0]));
expect(rslt.toJSON()).toEqual([1, 2]);
expect(range.toJSON()).toEqual([1, 2]);
});
it('encodes', (): void => {
+33 -12
View File
@@ -1,25 +1,32 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec, Constructor, InterfaceTypes, Registry } from '../types';
import type { AnyTuple, Constructor, INumber, Registry } from '../types';
import { Tuple } from '../codec/Tuple';
type RangeType = 'Range' | 'RangeInclusive';
/**
* @name Range
* @description
* Rust `Range<T>` representation
*/
export class Range<T extends Codec> extends Tuple {
constructor (registry: Registry, ty: Constructor<T> | keyof InterfaceTypes, value: [T, T]) {
super(
registry,
{
end: ty,
start: ty
},
value
);
export class Range<T extends INumber> extends Tuple {
#rangeName: RangeType;
constructor (registry: Registry, Type: Constructor<T> | string, value?: AnyTuple, rangeName: RangeType = 'Range') {
super(registry, { end: Type, start: Type }, value);
this.#rangeName = rangeName;
}
public static override with <T extends INumber> (Types: Constructor<T> | string): Constructor<Range<T>> {
return class extends Range<T> {
constructor (registry: Registry, value?: AnyTuple) {
super(registry, Types, value);
}
};
}
/**
@@ -40,6 +47,20 @@ export class Range<T extends Codec> extends Tuple {
* @description Returns the base runtime type name for this instance
*/
public override toRawType (): string {
return `Range<${this.start.toRawType()}>`;
return `${this.#rangeName}<${this.start.toRawType()}>`;
}
}
export class RangeInclusive<T extends INumber = INumber> extends Range<T> {
constructor (registry: Registry, type: Constructor<T> | string, value?: AnyTuple) {
super(registry, type, value, 'RangeInclusive');
}
public static override with <T extends INumber> (Types: Constructor<T> | string): Constructor<RangeInclusive<T>> {
return class extends RangeInclusive<T> {
constructor (registry: Registry, value?: AnyTuple) {
super(registry, Types, value);
}
};
}
}
@@ -1,34 +0,0 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { TypeRegistry } from '../create';
import { U32 } from '../primitive';
import { RangeInclusive } from '.';
describe('RangeInclusive', (): void => {
const registry = new TypeRegistry();
const Type = RangeInclusive.with([U32, U32]);
let range: RangeInclusive<U32>;
beforeEach((): void => {
range = new RangeInclusive(
registry,
U32,
[new U32(registry, 1), new U32(registry, 2)]
);
});
it('decodes', (): void => {
const rslt = new Type(registry, new Uint8Array([1, 0, 0, 0, 2, 0, 0, 0]));
expect(rslt.toJSON()).toEqual([1, 2]);
});
it('encodes', (): void => {
expect(range.toU8a()).toEqual(new Uint8Array([1, 0, 0, 0, 2, 0, 0, 0]));
});
it('has a sane toRawType representation', (): void => {
expect(range.toRawType()).toEqual('RangeInclusive<u32>');
});
});
@@ -1,45 +0,0 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Codec, Constructor, InterfaceTypes, Registry } from '../types';
import { Tuple } from '../codec/Tuple';
/**
* @name RangeInclusive
* @description
* Rust `RangeInclusive<T>` representation
*/
export class RangeInclusive<T extends Codec> extends Tuple {
constructor (registry: Registry, ty: Constructor<T> | keyof InterfaceTypes, value: [T, T]) {
super(
registry,
{
end: ty,
start: ty
},
value
);
}
/**
* @description Returns the starting range value
*/
public get start (): T {
return this[0] as T;
}
/**
* @description Returns the ending range value
*/
public get end (): T {
return this[1] as T;
}
/**
* @description Returns the base runtime type name for this instance
*/
public override toRawType (): string {
return `RangeInclusive<${this.start.toRawType()}>`;
}
}
+9 -5
View File
@@ -3,7 +3,7 @@
import type { AnyNumber, AnyString, AnyU8a, Codec, Constructor, ITuple, Registry } from '../types';
import { isHex, isU8a, stringify, u8aConcat, u8aToU8a } from '@polkadot/util';
import { isFunction, isHex, isString, isU8a, stringify, u8aConcat, u8aToU8a } from '@polkadot/util';
import { AbstractArray } from './AbstractArray';
import { decodeU8a, mapToTypeMap, typeToConstructor } from './utils';
@@ -14,7 +14,9 @@ type TupleConstructors = Constructor[] | {
[index: string]: Constructor;
};
type TupleTypes = (Constructor | string)[] | {
type TupleType = (Constructor | string);
type TupleTypes = TupleType[] | {
[index: string]: Constructor | string;
};
@@ -52,17 +54,19 @@ function decodeTuple (registry: Registry, _Types: TupleConstructors, value?: Any
export class Tuple extends AbstractArray<Codec> implements ITuple<Codec[]> {
private _Types: TupleConstructors;
constructor (registry: Registry, Types: TupleTypes, value?: AnyTuple) {
constructor (registry: Registry, Types: TupleTypes | TupleType, value?: AnyTuple) {
const Clazzes = Array.isArray(Types)
? Types.map((t) => typeToConstructor(registry, t))
: mapToTypeMap(registry, Types);
: isFunction(Types) || isString(Types)
? [typeToConstructor(registry, Types)]
: mapToTypeMap(registry, Types);
super(registry, ...decodeTuple(registry, Clazzes, value));
this._Types = Clazzes;
}
public static with (Types: TupleTypes): Constructor<Tuple> {
public static with (Types: TupleTypes | TupleType): Constructor<Tuple> {
return class extends Tuple {
constructor (registry: Registry, value?: AnyTuple) {
super(registry, Types, value);
+1 -2
View File
@@ -19,10 +19,9 @@ export { Json } from './Json';
export { Linkage } from './Linkage';
export { CodecMap, CodecMap as Map } from './Map';
export { Option } from './Option';
export { Range, RangeInclusive } from './Range';
export { Raw } from './Raw';
export { Result } from './Result';
export { Range } from './Range';
export { RangeInclusive } from './RangeInclusive';
export { CodecSet, CodecSet as Set } from './Set';
export { Struct } from './Struct';
export { Tuple } from './Tuple';
+4 -1
View File
@@ -7,7 +7,7 @@ import type { TypeDef } from './types';
import { assert, isNumber, isUndefined, stringify } from '@polkadot/util';
import { BTreeMap, BTreeSet, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Option, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed } from '../codec';
import { BTreeMap, BTreeSet, CodecSet, Compact, DoNotConstruct, Enum, HashMap, Int, Option, Range, RangeInclusive, Result, Struct, Tuple, U8aFixed, UInt, Vec, VecFixed } from '../codec';
import { Bytes, Null } from '../primitive';
import { getTypeDef } from './getTypeDef';
import { TypeDefInfo } from './types';
@@ -114,6 +114,9 @@ const infoMapping: Record<TypeDefInfo, (registry: Registry, value: TypeDef) => C
[TypeDefInfo.Plain]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
registry.getOrUnknown(value.type),
[TypeDefInfo.Range]: (registry: Registry, value: TypeDef): Constructor<Codec> =>
(value.type.includes('RangeInclusive') ? RangeInclusive : Range).with(getSubType(value)),
[TypeDefInfo.Result]: (registry: Registry, value: TypeDef): Constructor<Codec> => {
const [Ok, Err] = getTypeClassArray(value);
+2
View File
@@ -133,6 +133,8 @@ const encoders: Record<TypeDefInfo, (registry: Registry, typeDef: TypeDef) => st
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[TypeDefInfo.Plain]: (registry: Registry, typeDef: TypeDef) =>
typeDef.displayName || typeDef.type,
[TypeDefInfo.Range]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, typeDef.type.includes('RangeInclusive') ? 'RangeInclusive' : 'Range'),
[TypeDefInfo.Result]: (registry: Registry, typeDef: TypeDef) =>
encodeWithParams(registry, typeDef, 'Result'),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
+11
View File
@@ -142,6 +142,14 @@ function _decodeFixedVec (value: TypeDef, type: string, _: string, count: number
return value;
}
function _decodeRange (value: TypeDef, _: string, subType: string): TypeDef {
const Type = getTypeDef(subType);
value.sub = [Type, Type];
return value;
}
// decode a tuple
function _decodeTuple (value: TypeDef, _: string, subType: string, count: number): TypeDef {
value.sub = subType.length === 0
@@ -195,6 +203,9 @@ const nestedExtraction: [string, string, TypeDefInfo, (value: TypeDef, type: str
['BTreeMap<', '>', TypeDefInfo.BTreeMap, _decodeTuple],
['HashMap<', '>', TypeDefInfo.HashMap, _decodeTuple],
['Int<', '>', TypeDefInfo.Int, _decodeInt],
// Not sure about these, have a specific implementation?
['Range<', '>', TypeDefInfo.Tuple, _decodeRange],
['RangeInclusive<', '>', TypeDefInfo.Tuple, _decodeRange],
['Result<', '>', TypeDefInfo.Result, _decodeTuple],
['UInt<', '>', TypeDefInfo.UInt, _decodeUInt],
['DoNotConstruct<', '>', TypeDefInfo.DoNotConstruct, _decodeDoNotConstruct]
+1 -1
View File
@@ -8,7 +8,7 @@ interface SanitizeOptions {
type Mapper = (value: string, options?: SanitizeOptions) => string;
const BOUNDED = ['BTreeMap', 'BTreeSet', 'HashMap', 'Vec'];
const ALLOWED_BOXES = BOUNDED.concat(['Compact', 'DoNotConstruct', 'Int', 'Linkage', 'Result', 'Option', 'UInt']);
const ALLOWED_BOXES = BOUNDED.concat(['Compact', 'DoNotConstruct', 'Int', 'Linkage', 'Range', 'RangeInclusive', 'Result', 'Option', 'UInt']);
const BOX_PRECEDING = ['<', '(', '[', '"', ',', ' ']; // start of vec, tuple, fixed array, part of struct def or in tuple
const mappings: Mapper[] = [
+1
View File
@@ -20,6 +20,7 @@ export enum TypeDefInfo {
UInt,
DoNotConstruct,
Si,
Range,
// anything not fully supported (keep this as the last entry)
Null
}
+13 -16
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2021 @polkadot/types authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BTreeMap, BTreeSet, CodecSet, Compact, Enum, HashMap, Linkage, Option, Raw, Struct, Vec, VecFixed } from '../codec';
import type { BTreeMap, BTreeSet, CodecSet, Compact, Enum, HashMap, Linkage, Option, Range, RangeInclusive, Raw, Result, Struct, Vec, VecFixed } from '../codec';
import type { Bytes, Null, u8 } from '../primitive';
import type { Codec, Constructor } from './codec';
import type { ICompact, IEnum, IMap, IMethod, INumber, IOption, IResult, ISet, IStruct, ITuple, IU8a, IVec } from './interfaces';
@@ -42,6 +42,8 @@ export type __MapWrapOne<C extends Codec> = {
'Compact<': C extends INumber ? Compact<C> : Codec;
'Linkage<': Linkage<C>;
'Option<': Option<C>;
'Range<': C extends INumber ? Range<C> : Codec;
'RangeInclusive<': C extends INumber ? RangeInclusive<C> : Codec;
'Vec<': C extends u8 ? Bytes : Vec<C>;
'[': C extends u8 ? Raw : VecFixed<C>;
};
@@ -51,6 +53,7 @@ export type __MapWrapOne<C extends Codec> = {
export type __MapWrapTwo<K extends Codec, V extends Codec> = {
'BTreeMap<': BTreeMap<K, V>;
'HashMap<': HashMap<K, V>;
'Result<': Result<K, V>;
};
export type __WrapOne = keyof __MapWrapOne<Codec>;
@@ -73,31 +76,25 @@ export type __ToTuple<O extends Codec[]> =
: O[0]
: Null;
export type __CodecFirst<K extends unknown, C extends Codec[], X extends unknown[]> = [
export type __CodecFirst<K extends unknown> =
K extends keyof InterfaceTypes
? InterfaceTypes[K]
: K extends unknown[]
? __ToTuple<__Codecs<K>>
: K extends Record<string, unknown>
? __ToStruct<K>
: K extends __WrapOne
? __MapWrapOne<C[0]>[K]
: K extends __WrapTwo
? __MapWrapTwo<C[0], C[1]>[K]
: Codec,
...X
];
: Codec;
export type __CodecsNext<K extends unknown, C extends Codec[]> =
K extends __WrapOne
? C extends [Codec, ...infer X]
? __CodecFirst<K, C, X>
: never
? [__MapWrapOne<C[0]>[K], ...X]
: Codec
: K extends __WrapTwo
? C extends [Codec, Codec, ...infer X]
? __CodecFirst<K, C, X>
: never
: __CodecFirst<K, C, C>;
? [__MapWrapTwo<C[0], C[1]>[K], ...X]
: Codec
: [__CodecFirst<K>, ...C];
export type __Codecs<T extends unknown[]> =
T extends [infer K, ...infer N]
@@ -141,13 +138,13 @@ export type __TokenizeKnown<K extends string, V extends __Value[], I extends str
// NOTE For recursion limits, it is more optimal to use __Sanitize with conjunction with __Tokenize
// below, even while we do more matching (Number of characters iterated through is the most problematic)
export type __Tokenize<K extends string, V extends __Value[] = [], I extends string = ''> =
K extends '' | ')' | '>' | '}'
K extends '' | '>' | ')' | '}'
? [__Combine<V, I>, '']
: K extends `${__Wrap}${infer R}`
? __TokenizeWrapped<K, V, I, R>
: K extends `${',' | '>'}${infer R}`
? __Tokenize<R, __Combine<V, I>>
: K extends `)${infer R}` | `}${infer R}`
: K extends `${')' | '}'}${infer R}`
? [__Combine<V, I>, R]
: K extends `(${infer R}`
? __TokenizeTuple<__Tokenize<R>, V, I>