isAscii adjustments (#1137)

* isAscii adjustments

* Adjust negation
This commit is contained in:
Jaco
2021-10-23 11:52:41 +03:00
committed by GitHub
parent da38e0f890
commit 2cc2c4d415
3 changed files with 17 additions and 2 deletions
+8
View File
@@ -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);
});
});
+8 -2
View File
@@ -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;
}