Allow ConsensusEngineId toString with non-ascii (#3315)
* Allow ConsensusEngineId toString with non-ascii * Add number test
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
// Copyright 2017-2021 @polkadot/types authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { hexToBn } from '@polkadot/util';
|
||||
|
||||
import { CID_AURA, CID_BABE, CID_GRPA, GenericConsensusEngineId as ConsensusEngineId } from './ConsensusEngineId';
|
||||
|
||||
describe('ConsensusEngineId', (): void => {
|
||||
@@ -12,4 +14,9 @@ describe('ConsensusEngineId', (): void => {
|
||||
it('reverses an id to string for babe', (): void => {
|
||||
expect(ConsensusEngineId.idToString(CID_BABE)).toEqual('BABE');
|
||||
});
|
||||
|
||||
it('reverses a non-ASCII id to a hex string', (): void => {
|
||||
expect(ConsensusEngineId.idToString(hexToBn('0x01020304', { isLe: true }))).toEqual('0x01020304');
|
||||
expect(ConsensusEngineId.idToString(0x04030201)).toEqual('0x01020304');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { AccountId } from '../interfaces/runtime';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { bnToBn } from '@polkadot/util';
|
||||
import { bnToU8a, isAscii, u8aToHex, u8aToString } from '@polkadot/util';
|
||||
|
||||
import { Bytes } from '../primitive/Bytes';
|
||||
import { u32 } from '../primitive/U32';
|
||||
@@ -24,10 +24,11 @@ export const CID_POW = 0x5f776f70; // 'pow_'
|
||||
*/
|
||||
export class GenericConsensusEngineId extends u32 {
|
||||
public static idToString (input: number | BN): string {
|
||||
return bnToBn(input)
|
||||
.toArray('le')
|
||||
.map((code): string => String.fromCharCode(code))
|
||||
.join('');
|
||||
const u8a = bnToU8a(input);
|
||||
|
||||
return isAscii(u8a)
|
||||
? u8aToString(u8a)
|
||||
: u8aToHex(u8a);
|
||||
}
|
||||
|
||||
public static stringToId (input: string): number {
|
||||
|
||||
Reference in New Issue
Block a user