@@ -8,6 +8,10 @@ describe('isAscii', (): void => {
|
||||
expect(isAscii('Hello\tWorld!\n\rTesting')).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false on an non-ascii string', (): void => {
|
||||
expect(isAscii('你好,世界')).toEqual(false);
|
||||
});
|
||||
|
||||
it('returns true for ASCII bytes', (): void => {
|
||||
expect(isAscii(new Uint8Array([0x31, 0x32, 0x20, 10]))).toEqual(true);
|
||||
});
|
||||
@@ -27,4 +31,8 @@ describe('isAscii', (): void => {
|
||||
it('returns false for non-printable characters', (): void => {
|
||||
expect(isAscii(new Uint8Array([5]))).toEqual(false);
|
||||
});
|
||||
|
||||
it('returns false for hex input, non-ascii', (): void => {
|
||||
expect(isAscii('0x010203')).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import type { U8aLike } from '../types';
|
||||
|
||||
import { u8aToU8a } from '../u8a/toU8a';
|
||||
import { isHex } from './hex';
|
||||
import { isString } from './string';
|
||||
|
||||
const FORMAT = [9, 10, 13];
|
||||
@@ -15,7 +16,12 @@ const FORMAT = [9, 10, 13];
|
||||
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
|
||||
*/
|
||||
export function isAscii (value?: U8aLike | null): boolean {
|
||||
const isStringIn = isString(value);
|
||||
|
||||
return value
|
||||
? !u8aToU8a(value).some((byte) => (byte >= 127) || (byte < 32 && !FORMAT.includes(byte)))
|
||||
: isString(value);
|
||||
? (isStringIn && !isHex(value)
|
||||
? value.toString().split('').map((s) => s.charCodeAt(0))
|
||||
: u8aToU8a(value)
|
||||
).every((b) => (b < 127) && ((b >= 32) || FORMAT.includes(b)))
|
||||
: isStringIn;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user