Raw/Bytes isUtf8 & assert in toUtf8 (#2414)

This commit is contained in:
Jaco Greeff
2020-07-08 16:24:13 +02:00
committed by GitHub
parent 0e1bbd5cac
commit 2395401a2b
13 changed files with 73 additions and 58 deletions
+3 -3
View File
@@ -28,15 +28,15 @@
"dependencies": {
"@babel/runtime": "^7.10.4",
"@polkadot/metadata": "1.24.0-beta.0",
"@polkadot/util": "^2.18.0-beta.1",
"@polkadot/util-crypto": "^2.18.0-beta.1",
"@polkadot/util": "^2.18.0-beta.2",
"@polkadot/util-crypto": "^2.18.0-beta.2",
"@types/bn.js": "^4.11.6",
"bn.js": "^5.1.2",
"memoizee": "^0.4.14",
"rxjs": "^6.6.0"
},
"devDependencies": {
"@polkadot/keyring": "^2.18.0-beta.1",
"@polkadot/keyring": "^2.18.0-beta.2",
"@types/memoizee": "^0.4.4"
}
}
+6
View File
@@ -84,5 +84,11 @@ describe('Raw', (): void => {
expect(new Raw(registry, 'Приветствую, ми').toUtf8()).toEqual('Приветствую, ми');
expect(new Raw(registry, '0xe4bda0e5a5bd').toUtf8()).toEqual('你好');
});
it('throws on invalid utf8', (): void => {
expect(
() => new Raw(registry, '0x7f07b1f87709608bee603bbc79a0dfc29cd315c1351a83aa31adf7458d7d3003').toUtf8()
).toThrow(/The character sequence is not a valid Utf8 string/);
});
});
});
+10 -1
View File
@@ -5,7 +5,7 @@
import { H256 } from '../interfaces/runtime';
import { AnyJson, AnyU8a, IU8a, Registry } from '../types';
import { isAscii, isU8a, isUndefined, u8aToHex, u8aToString, u8aToU8a } from '@polkadot/util';
import { assert, isAscii, isU8a, isUndefined, isUtf8, u8aToHex, u8aToString, u8aToU8a } from '@polkadot/util';
import { blake2AsU8a } from '@polkadot/util-crypto';
/** @internal */
@@ -63,6 +63,13 @@ export default class Raw extends Uint8Array implements IU8a {
return !this.length || isUndefined(this.find((value) => !!value));
}
/**
* @description Returns true if the wrapped value contains only utf8 characters
*/
public get isUtf8 (): boolean {
return isUtf8(this);
}
/**
* @description The length of the value
*/
@@ -147,6 +154,8 @@ export default class Raw extends Uint8Array implements IU8a {
* @description Returns the wrapped data as a UTF-8 string
*/
public toUtf8 (): string {
assert(this.isUtf8, 'The character sequence is not a valid Utf8 string');
return u8aToString(this);
}
}