Refactor code structure for improved readability and maintainability

This commit is contained in:
2025-12-27 05:09:15 +00:00
parent 2d80d53b70
commit 8b95824cb6
7 changed files with 414 additions and 465 deletions
@@ -1,17 +1,31 @@
import type { BytesLike } from './BytesLike.js';
export function convertBytesLikeToUint8Array(data: BytesLike, encodeUTF8 = true): Uint8Array {
export function convertBytesLikeToUint8Array(
data: BytesLike,
encodeUTF8 = true
): Uint8Array<ArrayBuffer> {
if (data instanceof Uint8Array) {
return data;
if (
data.buffer instanceof ArrayBuffer
&& data.byteOffset === 0
&& data.byteLength === data.buffer.byteLength
) {
return data;
}
return new Uint8Array(data) as Uint8Array<ArrayBuffer>;
}
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
if (data instanceof DataView) {
const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
return new Uint8Array(view) as Uint8Array<ArrayBuffer>;
}
if (typeof (data) === 'string') {
if (encodeUTF8) {
return (new TextEncoder()).encode(data);
return (new TextEncoder()).encode(data) as Uint8Array<ArrayBuffer>;
}
return new Uint8Array(data.split('').map((s) => s.codePointAt(0) as number));
return new Uint8Array(data.split('').map((s) => s.codePointAt(0) as number)) as Uint8Array<ArrayBuffer>;
}
return new Uint8Array(data.buffer);
throw new Error('Unsupported BytesLike');
}