Allow Text to construct from hex (#1018)

* Allow Text to construct from hex

* Simplify decodeText
This commit is contained in:
Jaco Greeff
2019-06-17 10:40:59 +02:00
committed by GitHub
parent a9e3b88cdd
commit 683ed396c2
2 changed files with 10 additions and 7 deletions
+4 -3
View File
@@ -8,9 +8,9 @@ import Text from './Text';
describe('Text', () => {
describe('decode', () => {
const testDecode = (type: string, input: string | Uint8Array | { toString: () => string }, expected: string) =>
const testDecode = (type: string, input: string | Uint8Array | { toString: () => string }, expected: string, toFn: 'toString' | 'toHex' = 'toString') =>
it(`can decode from ${type}`, () => {
expect(new Text(input).toString()).toBe(expected);
expect(new Text(input)[toFn]()).toBe(expected);
});
testDecode('string', 'foo', 'foo');
@@ -18,6 +18,7 @@ describe('Text', () => {
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 (): string { return 'foo'; } }, 'foo');
testDecode('hex input value', new Text('0x12345678'), '0x12345678', 'toHex');
});
describe('encode', () => {
@@ -26,7 +27,7 @@ describe('Text', () => {
expect(new Text('foo')[to]()).toEqual(expected);
});
testEncode('toHex', '0x0c666f6f');
testEncode('toHex', '0x666f6f');
testEncode('toString', 'foo');
testEncode('toU8a', Uint8Array.from([12, 102, 111, 111]));
});
+6 -4
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { assert, isString, stringToU8a, u8aToString, u8aToHex } from '@polkadot/util';
import { assert, hexToU8a, isHex, isString, stringToU8a, u8aToString, u8aToHex } from '@polkadot/util';
import { AnyU8a, Codec } from '../types';
import Compact from '../codec/Compact';
@@ -28,8 +28,8 @@ export default class Text extends String implements Codec {
}
private static decodeText (value: Text | string | AnyU8a | { toString: () => string }): string {
if (isString(value)) {
return value.toString();
if (isHex(value)) {
return u8aToString(hexToU8a(value.toString()));
} else if (value instanceof Uint8Array) {
if (!value.length) {
return '';
@@ -81,7 +81,9 @@ export default class Text extends String implements Codec {
* @description Returns a hex string representation of the value
*/
toHex (): string {
return u8aToHex(this.toU8a());
// like with Vec<u8>, when we are encoding to hex, we don't actually add
// the length prefix (it is already implied by the actual string length)
return u8aToHex(this.toU8a(true));
}
/**