UNPKG

1.08 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { u8aToU8a } from "./toU8a.js";
4/**
5 * @name u8aEq
6 * @summary Compares two Uint8Arrays for equality.
7 * @description
8 * For `UInt8Array` (or hex string) input values true if there is a match.
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * import { u8aEq } from '@polkadot/util';
14 *
15 * u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
16 * ```
17 */
18
19export function u8aEq(a, b) {
20 const u8aa = u8aToU8a(a);
21 const u8ab = u8aToU8a(b);
22
23 if (u8aa.length === u8ab.length) {
24 const dvA = new DataView(u8aa.buffer, u8aa.byteOffset);
25 const dvB = new DataView(u8ab.buffer, u8ab.byteOffset);
26 const mod = u8aa.length % 4;
27 const length = u8aa.length - mod;
28
29 for (let i = 0; i < length; i += 4) {
30 if (dvA.getUint32(i) !== dvB.getUint32(i)) {
31 return false;
32 }
33 }
34
35 for (let i = length; i < u8aa.length; i++) {
36 if (u8aa[i] !== u8ab[i]) {
37 return false;
38 }
39 }
40
41 return true;
42 }
43
44 return false;
45}
\No newline at end of file