-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbuffer.ts
More file actions
75 lines (62 loc) · 2.02 KB
/
buffer.ts
File metadata and controls
75 lines (62 loc) · 2.02 KB
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
73
74
75
import { config } from '../config';
// Helper to convert bytes to hex string
const bytesToHex = (bytes: Uint8Array): string => {
return Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
};
// Helper to convert hex string to bytes
const hexToBytes = (hex: string): Uint8Array => {
if (hex.length % 2 !== 0) {
throw new Error('Hex string must have an even number of characters');
}
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
}
return bytes;
};
// Buffer polyfill for browser environments
export const createBuffer = (input: string, encoding?: BufferEncoding): Uint8Array => {
if (!config.isBrowser) {
return Buffer.from(input, encoding);
}
// Handle base64 encoding specifically
if (encoding === 'base64') {
const binaryString = atob(input);
return new Uint8Array(binaryString.length).map((_, i) => binaryString.charCodeAt(i));
}
// Default to UTF-8 encoding
return new TextEncoder().encode(input);
};
export const bufferToString = (buffer: Uint8Array, encoding?: BufferEncoding): string => {
if (!config.isBrowser) {
return Buffer.from(buffer).toString(encoding);
}
// Handle hex encoding specifically
if (encoding === 'hex') {
return bytesToHex(buffer);
}
// Handle base64 encoding specifically
if (encoding === 'base64') {
const binary = String.fromCharCode(...buffer);
return btoa(binary);
}
// Default to UTF-8 encoding
return new TextDecoder().decode(buffer);
};
export const concatBuffers = (...buffers: Uint8Array[]): Uint8Array => {
if (!config.isBrowser) {
return Buffer.concat(buffers);
}
// Calculate total length
const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
// Create new array and copy all buffers into it
const result = new Uint8Array(totalLength);
let offset = 0;
for (const buffer of buffers) {
result.set(buffer, offset);
offset += buffer.length;
}
return result;
};