UNPKG

1.2 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { u8aToU8a } from "../u8a/toU8a.js";
4import { isHex } from "./hex.js";
5import { isString } from "./string.js";
6/** @internal */
7
8function isAsciiStr(str) {
9 const count = str.length;
10
11 for (let i = 0; i < count; i++) {
12 const b = str.charCodeAt(i); // check is inlined here, it is faster than making a call
13
14 if (!(b < 127 && (b >= 32 || b === 10 || b === 9 || b === 13))) {
15 return false;
16 }
17 }
18
19 return true;
20}
21/** @internal */
22
23
24function isAsciiBytes(u8a) {
25 const count = u8a.length;
26
27 for (let i = 0; i < count; i++) {
28 const b = u8a[i]; // check is inlined here, it is faster than making a call
29
30 if (!(b < 127 && (b >= 32 || b === 10 || b === 9 || b === 13))) {
31 return false;
32 }
33 }
34
35 return true;
36}
37/**
38 * @name isAscii
39 * @summary Tests if the input is printable ASCII
40 * @description
41 * Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
42 */
43
44
45export function isAscii(value) {
46 return isString(value) ? isHex(value) ? isAsciiBytes(u8aToU8a(value)) : isAsciiStr(value) : value ? isAsciiBytes(value) : false;
47}
\No newline at end of file