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 -1
View File
@@ -1,2 +1,2 @@
export type Bytes = ArrayBuffer | DataView | Uint8Array;
export type Bytes = ArrayBuffer | DataView | Uint8Array<ArrayBuffer>;
export type BytesLike = Bytes | string;
+2 -2
View File
@@ -121,7 +121,7 @@ export class LiteHashDRBG implements RNG {
return maxInt;
}
public nextBytes(bytes: number, baseBytes?: number): Uint8Array {
public nextBytes(bytes: number, baseBytes?: number): Uint8Array<ArrayBuffer> {
bytes |= 0;
if (bytes <= 0) {
throw new Error(`${bytes} <= 0`);
@@ -171,7 +171,7 @@ export class LiteHashDRBG implements RNG {
return result;
}
public nextBits(bits: number, baseBytes?: number): Uint8Array {
public nextBits(bits: number, baseBytes?: number): Uint8Array<ArrayBuffer> {
bits |= 0;
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
+2 -2
View File
@@ -5,8 +5,8 @@ export interface RNG {
*/
getMaxInt(): number;
nextBytes(bytes: number): Uint8Array;
nextBits(bits: number): Uint8Array;
nextBytes(bytes: number): Uint8Array<ArrayBuffer>;
nextBits(bits: number): Uint8Array<ArrayBuffer>;
nextInt(max?: number): number;
nextFloat1(): number;
@@ -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');
}