Intelligent constructor (#217)

* Decode Uint8Array to Struct

* Add decode for Text

* Add tests for Text

* Add decode for Struct

* Rename variable

* Add test for struct

* Remove array check

* Remove isTuple

* Remove decode in Struct

* Add encoding tests

* Remove isTuple

* Better error message

* Add isTuple back

* Fix Option

* Fix Metadata test

* Fix Vector

* Fix Enum

* Fix U8a

* Fix imports

* Add tests

* Fix bug new Compact

* Fix lint

* Use specific decode

* Fix Vector

* Fix test

* Remove useless file

* Don't change Vector

* Fix lint
This commit is contained in:
Amaury Martiny
2018-10-09 15:59:45 +02:00
committed by Jaco Greeff
parent 1263e5fb65
commit c026ecb1c2
14 changed files with 267 additions and 62 deletions
+2 -2
View File
@@ -42,7 +42,7 @@ export default class Method extends MethodIndex {
this._data = Method.encode(this._meta, this._args);
}
static decode (meta: FunctionMetadata, data: Uint8Array): Array<Base> {
static decodeMethod (meta: FunctionMetadata, data: Uint8Array): Array<Base> {
let offset = 0;
return Method.filterOrigin(meta).map(({ type }) => {
@@ -115,7 +115,7 @@ export default class Method extends MethodIndex {
const startData = super.byteLength();
this._meta = Method.findFunction(this.callIndex).meta;
this._args = Method.decode(this._meta, input.subarray(startData));
this._args = Method.decodeMethod(this._meta, input.subarray(startData));
const argsLength = this._args.reduce((length, arg) => length + arg.byteLength(), 0);
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2017-2018 @polkadot/types authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import Text from './Text';
import U8a from './codec/U8a';
const testDecode = (type, input, expected) =>
it(`can decode from ${type}`, () => {
expect(new Text(input).toString()).toBe(expected);
});
const testEncode = (to, expected) =>
it(`can encode ${to}`, () => {
expect(new Text('foo')[to]()).toEqual(expected);
});
describe('Text', () => {
testDecode('string', 'foo', 'foo');
testDecode('Text', new Text('foo'), 'foo');
testDecode('Uint8Array', Uint8Array.from([12, 102, 111, 111]), 'foo');
testDecode('U8a', new U8a(Uint8Array.from([12, 102, 111, 111])), 'foo');
testDecode('object with `toString()`', { toString() { return 'foo'; } }, 'foo');
// testEncode('toHex', '0x0c666f6f'); // FIXME Add this
testEncode('toString', 'foo');
testEncode('toU8a', Uint8Array.from([12, 102, 111, 111]));
});
+23 -4
View File
@@ -2,12 +2,16 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import isFunction from '@polkadot/util/is/function';
import isString from '@polkadot/util/is/string';
import u8aFromUtf8 from '@polkadot/util/u8a/fromUtf8';
import u8aToUtf8 from '@polkadot/util/u8a/toUtf8';
import u8aConcat from '@polkadot/util/u8a/concat';
import { AnyU8a } from '@polkadot/types/types';
import Base from './codec/Base';
import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
import U8a from './codec/U8a';
// This is a string wrapper, along with the length. It is used both for strings as well
// as stuff like documentation.
@@ -18,14 +22,29 @@ import Compact, { DEFAULT_LENGTH_BITS } from './codec/Compact';
// wraps the `Balance`, `T::AccountId`, etc. The reasoning - with a "TypeString"
// we can nicely strip types down like "T::AcountId" -> "AccountId"
export default class Text extends Base<string> {
constructor (value: Text | string = '') {
constructor (value: Text | string | AnyU8a = '') {
super(
value instanceof Text
? value.raw
: value.trim()
Text.decodeText(value)
);
}
static decodeText (input: any): string {
if (isString(input)) {
return input;
} else if (input instanceof Text) {
return input.raw;
} else if (input instanceof Uint8Array) {
const [offset, length] = Compact.decodeU8a(input, DEFAULT_LENGTH_BITS);
return u8aToUtf8(input.subarray(offset, offset + length.toNumber()));
} else if (input instanceof U8a) {
return Text.decodeText(input.raw);
} else if (isFunction(input.toString)) {
return input.toString();
} else {
return `${input}`;
}
}
get length (): number {
return this.raw.length;
}
+26 -1
View File
@@ -4,7 +4,32 @@
import Enum from './Enum';
describe('Struct', () => {
const testDecode = (type, input, expected) =>
it(`can decode from ${type}`, () => {
const e = new Enum(['foo', 'bar'], input);
expect(e.toString()).toBe(expected);
});
const testEncode = (to, expected) =>
it(`can encode ${to}`, () => {
const e = new Enum(['foo', 'bar'], 1);
expect(e[to]()).toEqual(expected);
});
describe('Enum', () => {
testDecode('Enum', undefined, 'foo');
testDecode('Enum', new Enum([], 1), 'bar');
testDecode('number', 0, 'foo');
testDecode('number', 1, 'bar');
testDecode('Uint8Array', Uint8Array.from([0]), 'foo');
testDecode('Uint8Array', Uint8Array.from([1]), 'bar');
testEncode('toJSON', 1);
testEncode('toNumber', 1);
testEncode('toString', 'bar');
testEncode('toU8a', Uint8Array.from([1]));
it('provides a clean toString()', () => {
expect(
new Enum(['foo', 'bar']).toString()
+13 -3
View File
@@ -2,6 +2,8 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import isU8a from '@polkadot/util/is/u8a';
import Base from './Base';
type EnumDef = {
@@ -20,14 +22,22 @@ export default class Enum extends Base<number> {
constructor (def: EnumDef, value: Enum | number = 0) {
super(
value instanceof Enum
? value.raw
: value
Enum.decodeEnum(value)
);
this._enum = def;
}
static decodeEnum (value: Enum | number = 0): number {
if (value instanceof Enum) {
return value.raw;
} else if (isU8a(value)) {
return value[0];
} else {
return value;
}
}
byteLength (): number {
return 1;
}
+20 -11
View File
@@ -5,20 +5,29 @@
import Option from './Option';
import Text from '../Text';
const testDecode = (type, input, expected) =>
it(`can decode from ${type}`, () => {
const o = new Option(Text, input);
expect(o.isEmpty).toBe(!expected.length)
expect(o.toString()).toBe(expected);
});
const testEncode = (to, expected) =>
it(`can encode ${to}`, () => {
const e = new Option(Text, 'foo');
expect(e[to]()).toEqual(expected);
});
describe('Option', () => {
it('converts fromJSON() with', () => {
const o = new Option(Text).fromJSON('1234');
expect(o.isEmpty).toEqual(false);
expect(o.toString()).toEqual('1234');
});
testDecode('string (with)', 'foo', 'foo');
testDecode('string (without)', undefined, '');
testDecode('Uint8Array (with)', Uint8Array.from([1, 12, 102, 111, 111]), 'foo');
testDecode('Uint8Array (without)', Uint8Array.from([0]), '');
it('converts fromJSON() without', () => {
const o = new Option(Text, '1234').fromJSON();
expect(o.isEmpty).toEqual(true);
expect(o.toString()).toEqual('');
});
// testEncode('toHex', '0x010c666f6f'); // FIXME Add this
testEncode('toString', 'foo');
testEncode('toU8a', Uint8Array.from([1, 12, 102, 111, 111]));
it('has empty toString() (undefined)', () => {
expect(
+13 -5
View File
@@ -2,6 +2,7 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import isU8a from '@polkadot/util/is/u8a';
import isUndefined from '@polkadot/util/is/undefined';
import Base from './Base';
@@ -10,18 +11,25 @@ import Base from './Base';
// is value to follow. If the byte is `1` there is an actual value. So the Option
// implements that - decodes, checks for optionality and wraps the required structure
// with a value if/as required/found.
export default class Option <T> extends Base<Base<T>> {
export default class Option<T> extends Base<Base<T>> {
private _isEmpty: boolean;
constructor (Value: { new(value?: any): Base<T> }, value?: any) {
constructor (Type: { new(value?: any): Base<T> }, value?: any) {
super(
new Value(value)
Option.decodeOption(Type, value)
);
this._isEmpty = isUndefined(value);
this._isEmpty = isUndefined(value) || value.length <= 1;
}
static with <O> (Type: { new(value?: any): Base<O> }): { new(value?: any): Option<O> } {
static decodeOption<O> (Type: { new(value?: any): Base<O> }, value?: any): Base<O> {
if (isU8a(value)) {
return new Type(value.subarray(1));
}
return new Type(value);
}
static with<O> (Type: { new(value?: any): Base<O> }): { new(value?: any): Option<O> } {
return class extends Option<O> {
constructor (value?: any) {
super(Type, value);
+42
View File
@@ -5,8 +5,50 @@
import Struct from './Struct';
import Text from '../Text';
import U32 from '../U32';
import Vector from './Vector';
const testDecode = (type, input) =>
it(`can decode from ${type}`, () => {
const s = new Struct({
foo: Text,
bar: U32
}, input);
expect(s.keys()).toEqual(['foo', 'bar']);
expect(
s.values().map((v) =>
v.toString()
)
).toEqual(['bazzing', '69']);
});
const testEncode = (to, expected) =>
it(`can encode ${to}`, () => {
const s = new Struct({
foo: Text,
bar: U32
}, { foo: 'bazzing', bar: 69 });
expect(s[to]()).toEqual(expected);
});
describe('Struct', () => {
testDecode('object', { foo: 'bazzing', bar: 69 });
testDecode('Uint8Array', Uint8Array.from([28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]));
// testEncode('toHex', '0x1c62617a7a696e6745000000'); // FIXME Add this
testEncode('toU8a', Uint8Array.from([28, 98, 97, 122, 122, 105, 110, 103, 69, 0, 0, 0]));
testEncode('toString', '{foo: bazzing, bar: 69}');
it('decodes a more complicated type', () => {
const s = new Struct({
foo: Vector.with(Struct.with({
bar: Text
}))
}, { foo: [{ bar: 1 }, { bar: 2 }] });
expect(s.toString()).toBe('{foo: [{bar: 1}, {bar: 2}]}');
})
it('provides a clean toString()', () => {
expect(
new (
+48 -17
View File
@@ -2,19 +2,21 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import hexToU8a from '@polkadot/util/hex/toU8a';
import isHex from '@polkadot/util/is/hex';
import isObject from '@polkadot/util/is/object';
import isU8a from '@polkadot/util/is/u8a';
import u8aConcat from '@polkadot/util/u8a/concat';
import u8aToU8a from '@polkadot/util/u8a/toU8a';
import Base from './Base';
import isU8a from '@polkadot/util/is/u8a';
// A Struct defines an Object with key/values - where the values are Base<T> values. It removes
// a lot of repetition from the actual coding, define a structure type, pass it the key/Base<T>
// values in the constructor and it manages the decoding. It is important that the constructor
// values matches 100% to the order in th Rust code, i.e. don't go crazy and make it alphabetical,
// it needs to decoded in the specific defined order.
export default class Struct <
export default class Struct<
// The actual Class structure, i.e. key -> Class
S = { [index: string]: { new(...value: Array<any>): Base } },
// internal type, instance of classes mapped by key
@@ -23,13 +25,13 @@ export default class Struct <
V = { [K in keyof S]: any },
// type names, mapped by key, name of Class in S
E = { [K in keyof S]: string }
> extends Base<T> {
> extends Base<T> {
protected _jsonMap: Map<keyof S, string>;
protected _Types: E;
constructor (Types: S, value: V | Array<any> = {} as V, jsonMap: Map<keyof S, string> = new Map()) {
super(
Struct.decode(Types, value)
Struct.decodeStruct(Types, value)
);
this._jsonMap = jsonMap;
@@ -43,30 +45,59 @@ export default class Struct <
}, {} as E);
}
static decode <S, V, T> (Types: S, value: V | Array<any>): T {
static decodeStruct<S, V, T> (Types: S, value: any): T {
// l.debug(() => ['Struct.decode', { Types, value }]);
if (isHex(value)) {
return Struct.decodeStruct(Types, hexToU8a(value as string));
} else if (!value) {
return {} as T;
}
// `currentIndex` is only used when we have a UintArray/U8a as value. It's
// used to track at which index we are currently parsing in that array.
let currentIndex = 0;
return Object
.keys(Types)
.reduce((raw: T, key, index) => {
// FIXME Ok, something weird is going on here or I just don't get it...
// it works, so ignore the checker, although it drives me batty. (It started when
// the [key in keyof T] was added, the idea is to provide better checks, which
// does backfire here, but works externally.)
// @ts-ignore
raw[key] = value[key] instanceof Types[key]
// @ts-ignore
? value[key]
// @ts-ignore
: new Types[key](value[key]);
if (isU8a(value)) {
// @ts-ignore FIXME See below
raw[key] = new Types[key](
value.subarray(
currentIndex
)
);
// Move the currentIndex forward
// @ts-ignore FIXME See below
currentIndex += raw[key].byteLength();
// @ts-ignore FIXME See below
} else if (value[key] instanceof Types[key]) {
// @ts-ignore FIXME See below
raw[key] = value[key];
} else if (isObject(value)) {
// @ts-ignore FIXME Ok, something weird is going on here or I just don't get it...
// it works, so ignore the checker, although it drives me batty. (It started when
// the [key in keyof T] was added, the idea is to provide better checks, which
// does backfire here, but works externally.)
raw[key] = new Types[key](
// @ts-ignore FIXME
value[key]
);
} else {
// @ts-ignore FIXME
throw new Error(`Struct: cannot decode type "${Types[key].name}" with value "${value}".`);
}
return raw;
}, {} as T);
}
static with <
static with<
S = { [index: string]: { new(value?: any): Base } }
> (Types: S): { new(value?: any): Struct<S> } {
> (Types: S): { new(value?: any): Struct<S> } {
return class extends Struct<S> {
constructor (value?: any, jsonMap?: Map<keyof S, string>) {
super(Types, value, jsonMap);
+5 -5
View File
@@ -16,17 +16,17 @@ import Struct from './Struct';
// A Tuple defines an anonymous Object with key/values - where the values are Base<T> values.It
// is a specialization of the Struct type where the toJSON/fromJSON operates on Array structures,
// while the U8a encoding is handled in the same way as a Struct
export default class Tuple <
export default class Tuple<
// S & T definitions maps to what we have in Struct (naming documented there)
S = { [index: string]: { new(value?: any): Base } },
T = { [K in keyof S]: Base },
V = { [K in keyof S]: any }
> extends Struct<S, T, V> {
> extends Struct<S, T, V> {
constructor (Types: S, value?: V | AnyU8a, jsonMap?: Map<keyof S, string>) {
super(Types, Tuple.decodeU8a(Types, value), jsonMap);
}
static decodeU8a <S, V> (Types: S, _value: V | AnyU8a): V {
static decodeU8a<S, V> (Types: S, _value: V | AnyU8a): V {
if (!isU8a(_value) && !isString(_value) && !Array.isArray(_value)) {
return _value as V;
}
@@ -47,9 +47,9 @@ export default class Tuple <
}, {} as V);
}
static with <
static with<
S = { [index: string]: { new(value?: any): Base } }
> (Types: S): { new(value?: any): Tuple<S> } {
> (Types: S): { new(value?: any): Tuple<S> } {
return class extends Tuple<S> {
constructor (value?: any) {
super(Types, value);
+22
View File
@@ -4,6 +4,18 @@
import U8a from './U8a';
const testDecode = (type, input, expected) =>
it(`can decode from ${type}`, () => {
const e = new U8a(input);
expect(e.toString()).toBe(expected);
});
const testEncode = (to, expected) =>
it(`can encode ${to}`, () => {
const e = new U8a([1, 2, 3, 4, 5]);
expect(e[to]()).toEqual(expected);
});
describe('U8a', () => {
let u8a;
@@ -11,6 +23,16 @@ describe('U8a', () => {
u8a = new U8a([1, 2, 3, 4, 5]);
});
testDecode('Array', [1, 2, 3, 4, 5], '0x0102030405')
testDecode('hex', '0x0102030405', '0x0102030405');
testDecode('U8a', new Uint8Array([1, 2, 3, 4, 5]), '0x0102030405');
testDecode('Uint8Array', Uint8Array.from([1, 2, 3, 4, 5]), '0x0102030405');
testEncode('toJSON', '0x0102030405');
testEncode('toHex', '0x0102030405');
testEncode('toString', '0x0102030405');
testEncode('toU8a', Uint8Array.from([1, 2, 3, 4, 5]));
it('contains the length of the elements', () => {
expect(u8a.length).toEqual(5); // eslint-disable-line
});
+13 -5
View File
@@ -2,11 +2,11 @@
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
import { AnyU8a } from '../types';
import isU8a from '@polkadot/util/is/u8a';
import u8aToHex from '@polkadot/util/u8a/toHex';
import toU8a from '@polkadot/util/u8a/toU8a';
import { AnyU8a } from '../types';
import Base from './Base';
// A U8a. A basic wrapper around Uint8Array, with no frills and no fuss. It
@@ -16,12 +16,20 @@ import Base from './Base';
export default class U8a extends Base<Uint8Array> {
constructor (value: AnyU8a = new Uint8Array()) {
super(
value instanceof U8a
? value.raw
: toU8a(value)
U8a.decodeU8a(value)
);
}
static decodeU8a (value: any): Uint8Array {
if (isU8a(value)) {
return value;
} else if (value instanceof U8a) {
return value.raw;
} else {
return toU8a(value);
}
}
get length (): number {
return this.raw.length;
}
+3 -3
View File
@@ -32,14 +32,14 @@ export default class UInt extends Base<BN> {
constructor (value: AnyNumber = 0, bitLength: UIntBitLength = DEFAULT_UINT_BITS, isHexJson: boolean = true) {
super(
UInt.decode(value)
UInt.decodeUInt(value)
);
this._bitLength = bitLength;
this._isHexJson = isHexJson;
}
static decode (value: AnyNumber): BN {
static decodeUInt (value: AnyNumber): BN {
if (value instanceof UInt) {
return value.raw;
} else if (isHex(value)) {
@@ -59,7 +59,7 @@ export default class UInt extends Base<BN> {
}
fromJSON (input: any): UInt {
this.raw = UInt.decode(input);
this.raw = UInt.decodeUInt(input);
return this;
}
+8 -6
View File
@@ -13,9 +13,9 @@ import Compact, { DEFAULT_LENGTH_BITS } from './Compact';
// i.e. while it wraps an array, it provides a `length` property to get the actual length, `at(index)`
// to retrieve a specific item. Additionally the helper functions `map`, `filter`, `forEach` and
// `reduce` is exposed on the interface.
export default class Vector <
export default class Vector<
T extends Base
> extends Base<Array<T>> {
> extends Base<Array<T>> {
private _Type: { new(value?: any): T };
constructor (Type: { new(value?: any): T }, value: Uint8Array | string | Array<any> = [] as Array<any>) {
@@ -26,7 +26,7 @@ export default class Vector <
this._Type = Type;
}
static decode <T> (Type: { new(value?: any): T }, value: Uint8Array | string | Array<any>): Array<T> {
static decode<T> (Type: { new(value?: any): T }, value: Uint8Array | string | Array<any>): Array<T> {
if (Array.isArray(value)) {
return value.map((entry) =>
entry instanceof Type
@@ -43,6 +43,8 @@ export default class Vector <
const result = [];
for (let index = 0; index < length; index++) {
// FIXME replace by
// const decoded = new Type(u8a.subarray(offset));
// @ts-ignore Not sure why we get "Property 'fromU8a' does not exist on type 'T'.", T extends Base in def?
const decoded = new Type().fromU8a(u8a.subarray(offset));
@@ -53,7 +55,7 @@ export default class Vector <
return result;
}
static with <O extends Base> (Type: { new(value?: any): O }): { new(value?: any): Vector<O> } {
static with<O extends Base> (Type: { new(value?: any): O }): { new(value?: any): Vector<O> } {
return class extends Vector<O> {
constructor (value?: Array<any>) {
super(Type, value);
@@ -106,7 +108,7 @@ export default class Vector <
return this.raw[index];
}
map <O> (fn: (item: T, index?: number) => O): Array<O> {
map<O> (fn: (item: T, index?: number) => O): Array<O> {
return this.raw.map(fn);
}
@@ -114,7 +116,7 @@ export default class Vector <
this.raw.push(item);
}
reduce <O> (fn: (result: O, item: T, index?: number) => O, initial: O): O {
reduce<O> (fn: (result: O, item: T, index?: number) => O, initial: O): O {
return this.raw.reduce(fn, initial);
}