All files / bytes / starts_with.ts

100.00% Branches 5/5
100.00% Lines 9/9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x51
x57
x59
x59
 
x57
x68
x68
x60
x57

































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Returns `true` if the prefix array appears at the start of the source array,
 * `false` otherwise.
 *
 * The complexity of this function is `O(prefix.length)`.
 *
 * @param source Source array to check.
 * @param prefix Prefix array to check for.
 * @returns `true` if the prefix array appears at the start of the source array,
 * `false` otherwise.
 *
 * @example Basic usage
 * ```ts
 * import { startsWith } from "@std/bytes/starts-with";
 * import { assertEquals } from "@std/assert";
 *
 * const source = new Uint8Array([0, 1, 2, 1, 2, 1, 2, 3]);
 * const prefix = new Uint8Array([0, 1, 2]);
 *
 * assertEquals(startsWith(source, prefix), true);
 * ```
 */
export function startsWith(source: Uint8Array, prefix: Uint8Array): boolean {
  if (prefix.length > source.length) {
    return false;
  }

  for (let i = 0; i < prefix.length; i++) {
    if (source[i] !== prefix[i]) return false;
  }
  return true;
}