All files / encoding / _validate_binary_like.ts

100.00% Branches 12/12
100.00% Lines 24/24
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
 
 
x23
 
x29
x29
x29
x31
x29
x34
x33
x36
x36
x29
 
x23
x141
x221
x141
x312
x312
x325
x325
x261
x261
x261
x261
 
x141



























// Copyright 2018-2025 the Deno authors. MIT license.

const encoder = new TextEncoder();

function getTypeName(value: unknown): string {
  const type = typeof value;
  if (type !== "object") {
    return type;
  } else if (value === null) {
    return "null";
  } else {
    return value?.constructor?.name ?? "object";
  }
}

export function validateBinaryLike(source: unknown): Uint8Array {
  if (typeof source === "string") {
    return encoder.encode(source);
  } else if (source instanceof Uint8Array) {
    return source;
  } else if (source instanceof ArrayBuffer) {
    return new Uint8Array(source);
  }
  throw new TypeError(
    `Cannot validate the input as it must be a Uint8Array, a string, or an ArrayBuffer: received a value of the type ${
      getTypeName(source)
    }`,
  );
}