Refactor code structure for improved readability and maintainability
This commit is contained in:
@@ -1,2 +1,2 @@
|
||||
export type Bytes = ArrayBuffer | DataView | Uint8Array;
|
||||
export type Bytes = ArrayBuffer | DataView | Uint8Array<ArrayBuffer>;
|
||||
export type BytesLike = Bytes | string;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user