xref: /aosp_15_r20/external/pigweed/pw_hdlc/ts/util.ts (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1// Copyright 2021 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15/** Convenience methods for working with Uint8Array buffers */
16
17/**
18 * Returns a new array where all instances of target have been replaced by the
19 * provided substitue.
20 */
21export function replace(
22  data: Uint8Array,
23  target: number,
24  substitute: number[],
25): Uint8Array {
26  const result: number[] = [];
27  data.forEach((value) => {
28    if (value === target) {
29      result.push(...substitute);
30    } else {
31      result.push(value);
32    }
33  });
34  return Uint8Array.from(result);
35}
36
37/** Flattens the provided list of Uint8Arrays into a single array. */
38export function concatenate(...byteList: Uint8Array[]): Uint8Array {
39  const length = byteList.reduce(
40    (accumulator, bytes) => accumulator + bytes.length,
41    0,
42  );
43  const result = new Uint8Array(length);
44  let offset = 0;
45  byteList.forEach((value) => {
46    result.set(value, offset);
47    offset += value.length;
48  });
49  return result;
50}
51