Add isBase{32, 58, 64} utils (#689)
* Add isBase{32, 58, 64} utils
* Allow empty inputs
* Add base64{Trim, Pad}
* isBase64
* Update assert messages
* Cleaup ifsCompat checks
This commit is contained in:
@@ -24,20 +24,14 @@ const LOOKUP = BASE32_ALPHABET
|
||||
* From the provided input, decode the base32 and return the result as an `Uint8Array`.
|
||||
*/
|
||||
export default function base32Decode (value: string, ipfsCompat = false): Uint8Array {
|
||||
if (ipfsCompat) {
|
||||
assert(value[0] === 'b', "Expected IPFS base32 identifier 'b' at string start");
|
||||
validate(value, ipfsCompat);
|
||||
|
||||
value = value.substr(1);
|
||||
}
|
||||
|
||||
validate(value);
|
||||
|
||||
const out = new Uint8Array((value.length * BITS_PER_CHAR / 8) | 0);
|
||||
const out = new Uint8Array(((value.length - (ipfsCompat ? 1 : 0)) * BITS_PER_CHAR / 8) | 0);
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
let written = 0;
|
||||
|
||||
for (let i = 0; i < value.length; ++i) {
|
||||
for (let i = (ipfsCompat ? 1 : 0); i < value.length; ++i) {
|
||||
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[value[i]];
|
||||
bits += BITS_PER_CHAR;
|
||||
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
export { default as base32Decode } from './decode';
|
||||
export { default as base32Encode } from './encode';
|
||||
export { default as base32Validate } from './validate';
|
||||
export { default as isBase32 } from './is';
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import validate from './validate';
|
||||
|
||||
export default function isBase32 (value?: string | null): boolean {
|
||||
try {
|
||||
return validate(value);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { base32Validate } from '.';
|
||||
|
||||
describe('base32Validate', (): void => {
|
||||
it('validates ipfs-compat encoded', (): void => {
|
||||
expect(
|
||||
() => base32Validate('bafkreigh2akiscaildcqabsyg3dfr6chu3fgpregiymsck7e7aqa4s52zy', true)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,6 @@ import { BASE32_ALPHABET } from './bs32';
|
||||
* @description
|
||||
* Validates the the supplied value is valid base32
|
||||
*/
|
||||
export default function base32Validate (value: string): true {
|
||||
return validateChars('base32', BASE32_ALPHABET, value);
|
||||
export default function base32Validate (value?: string | null, ipfsCompat = false): true {
|
||||
return validateChars('base32', BASE32_ALPHABET, value, ipfsCompat ? 'b' : undefined);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user