-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Bytes.ts
72 lines (56 loc) · 1.61 KB
/
Bytes.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
/* eslint-disable class-methods-use-this */
import { Buffer } from 'buffer';
export class Bytes {
public fromBase64(value: string): Uint8Array {
return Buffer.from(value, 'base64');
}
public fromHex(value: string): Uint8Array {
return Buffer.from(value, 'hex');
}
// TODO(indutny): deprecate it
public fromBinary(value: string): Uint8Array {
return Buffer.from(value, 'binary');
}
public fromString(value: string): Uint8Array {
return Buffer.from(value);
}
public toBase64(data: Uint8Array): string {
return Buffer.from(data).toString('base64');
}
public toHex(data: Uint8Array): string {
return Buffer.from(data).toString('hex');
}
// TODO(indutny): deprecate it
public toBinary(data: Uint8Array): string {
return Buffer.from(data).toString('binary');
}
public toString(data: Uint8Array): string {
return Buffer.from(data).toString();
}
public byteLength(value: string): number {
return Buffer.byteLength(value);
}
public concatenate(list: ReadonlyArray<Uint8Array>): Uint8Array {
return Buffer.concat(list);
}
public isEmpty(data: Uint8Array | null | undefined): boolean {
if (!data) {
return true;
}
return data.length === 0;
}
public isNotEmpty(data: Uint8Array | null | undefined): data is Uint8Array {
return !this.isEmpty(data);
}
public areEqual(
a: Uint8Array | null | undefined,
b: Uint8Array | null | undefined
): boolean {
if (!a || !b) {
return !a && !b;
}
return Buffer.compare(a, b) === 0;
}
}