refactor: migrate RNG and utility functions to common package

- Removed RNG interface and related utility classes from logic package.
- Added RNG interface and utility classes in common package.
- Implemented various RNG classes (ConstantRNG, MidpointRNG, SineRNG, SequenceRNG) in common package.
- Updated conversion utilities for BytesLike to ArrayBuffer and Uint8Array in common package.
- Adjusted tests to import RNG utilities from the new common package.
- Updated vitest configuration to resolve common package imports.
This commit is contained in:
2025-12-28 12:27:47 +00:00
parent 27b243b121
commit fa22562bb1
17 changed files with 30 additions and 18 deletions
+8 -1
View File
@@ -1 +1,8 @@
export {};
export * from './rng.js';
export * from './util/BytesLike.js';
export * from './util/convertBytesLikeToArrayBuffer.js';
export * from './util/convertBytesLikeToUint8Array.js';
export * from './util/LiteHashDRBG.js';
export * from './util/RNG.js';
export * from './util/RandUtil.js';
export * from './util/TestRNG.js';
+5
View File
@@ -0,0 +1,5 @@
export interface RandomGenerator {
nextFloat(): number;
nextBool(probability: number): boolean;
nextInt(minInclusive: number, maxExclusive: number): number;
}
+2
View File
@@ -0,0 +1,2 @@
export type Bytes = ArrayBuffer | DataView<ArrayBuffer> | Uint8Array<ArrayBuffer>;
export type BytesLike = Bytes | string;
+234
View File
@@ -0,0 +1,234 @@
import type { RNG } from './RNG.js';
import { sha512 } from 'js-sha512';
import { convertBytesLikeToUint8Array } from './convertBytesLikeToUint8Array.js';
import type { BytesLike } from './BytesLike.js';
const maxRngSupportBit = 53;
const maxInt = 0x1f_ffff_ffff_ffff; // NOTE: b 0, 10000110011, 11...11
const maxIntMore1 = 0x20_0000_0000_0000n; //NOTE: b 0, 10000110100, 00...00
const maxIntMore1f = Number(maxIntMore1);
export const bufferByteSize = 512 / 8; //SHA512
const intBitMapMask = new Map([
[0x1n, 1],
[0x3n, 2],
[0x7n, 3],
[0xfn, 4],
[0x1fn, 5],
[0x3fn, 6],
[0x7fn, 7],
[0xffn, 8],
[0x1ffn, 9],
[0x3ffn, 10],
[0x7ffn, 11],
[0xfffn, 12],
[0x1fffn, 13],
[0x3fffn, 14],
[0x7fffn, 15],
[0xffffn, 16],
[0x1ffffn, 17],
[0x3ffffn, 18],
[0x7ffffn, 19],
[0xfffffn, 20],
[0x1fffffn, 21],
[0x3fffffn, 22],
[0x7fffffn, 23],
[0xffffffn, 24],
[0x1ffffffn, 25],
[0x3ffffffn, 26],
[0x7ffffffn, 27],
[0xfffffffn, 28],
[0x1fffffffn, 29],
[0x3fffffffn, 30],
[0x7fffffffn, 31],
[0xffffffffn, 32],
[0x1ffffffffn, 33],
[0x3ffffffffn, 34],
[0x7ffffffffn, 35],
[0xfffffffffn, 36],
[0x1fffffffffn, 37],
[0x3fffffffffn, 38],
[0x7fffffffffn, 39],
[0xffffffffffn, 40],
[0x1ffffffffffn, 41],
[0x3ffffffffffn, 42],
[0x7ffffffffffn, 43],
[0xfffffffffffn, 44],
[0x1fffffffffffn, 45],
[0x3fffffffffffn, 46],
[0x7fffffffffffn, 47],
[0xffffffffffffn, 48],
[0x1ffffffffffffn, 49],
[0x3ffffffffffffn, 50],
[0x7ffffffffffffn, 51],
[0xfffffffffffffn, 52],
[0x1fffffffffffffn, 53],
]);
function calcBitMask(n: bigint): bigint {
n |= n >> 1n;
n |= n >> 2n;
n |= n >> 4n;
n |= n >> 8n;
n |= n >> 16n;
n |= n >> 32n;
return n;
}
// SHA-512 기반 DRBG 구현
export class LiteHashDRBG implements RNG {
protected buffer!: ArrayBuffer;
protected bufferIdx!: number;
protected hq: DataView;
protected hqIdxPos: number;
public constructor(protected seed: BytesLike, protected stateIdx = 0, bufferIdx = 0) {
if (bufferIdx < 0) {
throw new Error(`bufferIdx ${bufferIdx} < 0`);
}
if (bufferIdx >= bufferByteSize) {
throw new Error(`bufferidx ${bufferIdx} >= ${bufferByteSize}`);
}
if (stateIdx < 0) {
throw new Error(`stateIdx ${stateIdx} < 0`);
}
const seedU8 = convertBytesLikeToUint8Array(seed);
const hqBuffer = new ArrayBuffer(seedU8.byteLength + 4);
const hqU8 = new Uint8Array(hqBuffer);
hqU8.set(seedU8, 0);
this.hq = new DataView(hqBuffer);
this.hqIdxPos = seedU8.byteLength;
this.genNextBlock();
this.bufferIdx = bufferIdx;
}
protected genNextBlock(): void {
this.hq.setUint32(this.hqIdxPos, this.stateIdx, true);
const digest = sha512.arrayBuffer(this.hq.buffer as ArrayBuffer);
this.buffer = digest;
this.bufferIdx = 0;
this.stateIdx += 1;
}
public getMaxInt(): number {
return maxInt;
}
public nextBytes(bytes: number, baseBytes?: number): Uint8Array<ArrayBuffer> {
bytes |= 0;
if (bytes <= 0) {
throw new Error(`${bytes} <= 0`);
}
if (this.bufferIdx + bytes <= bufferByteSize) {
if (baseBytes === undefined || bytes >= baseBytes) {
const result = this.buffer.slice(this.bufferIdx, this.bufferIdx + bytes);
this.bufferIdx += bytes;
if (this.bufferIdx === bufferByteSize) {
this.genNextBlock();
}
return new Uint8Array(result);
}
const resultBuffer = new ArrayBuffer(Math.max(bytes, baseBytes));
const result = new Uint8Array(resultBuffer);
result.set(new Uint8Array(this.buffer, this.bufferIdx, bytes));
this.bufferIdx += bytes;
if (this.bufferIdx === bufferByteSize) {
this.genNextBlock();
}
return result;
}
const resultBuffer = new ArrayBuffer(baseBytes ? Math.max(bytes, baseBytes) : bytes);
const result = new Uint8Array(resultBuffer);
result.set(new Uint8Array(this.buffer, this.bufferIdx));
let offset = bufferByteSize - this.bufferIdx;
let remain = bytes - offset;
while (remain > bufferByteSize) {
this.genNextBlock();
result.set(new Uint8Array(this.buffer), offset);
offset += bufferByteSize;
remain -= bufferByteSize;
}
this.genNextBlock();
if (remain === 0) {
return result;
}
result.set(new Uint8Array(this.buffer, 0, remain), offset);
this.bufferIdx = remain;
return result;
}
public nextBits(bits: number, baseBytes?: number): Uint8Array<ArrayBuffer> {
bits |= 0;
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
const result = this.nextBytes(bytes, baseBytes);
if (headBits === 0) {
return result;
}
result[bytes - 1]! &= 0xff >> (8 - headBits);
return result;
}
protected _nextInt(bits: number): bigint {
const buffer = this.nextBits(bits, 8);
const dataView = new DataView(buffer.buffer);
return dataView.getBigUint64(0, true);
}
public nextInt(max?: number): number {
if (max === undefined || max === maxInt) {
return Number(this._nextInt(maxRngSupportBit));
}
if (max > maxInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
const mask = calcBitMask(BigInt(max));
const bits = intBitMapMask.get(mask) as number;
let n = Number(this._nextInt(bits));
while (n > max) {
n = Number(this._nextInt(bits));
}
return n;
}
public nextFloat1(): number {
// eslint-disable-next-line no-constant-condition
while (true) {
const nInt = this._nextInt(maxRngSupportBit + 1);
if (nInt < maxIntMore1) {
return Number(nInt) / maxIntMore1f;
}
if (nInt === maxIntMore1) {
return 1;
}
}
}
public static build(seed: BytesLike, stateIdx = 0): LiteHashDRBG {
return new LiteHashDRBG(seed, stateIdx);
}
}
+13
View File
@@ -0,0 +1,13 @@
export interface RNG {
/**
* nextInt()가 반환 가능한 최댓값
*/
getMaxInt(): number;
nextBytes(bytes: number): Uint8Array<ArrayBuffer>;
nextBits(bits: number): Uint8Array<ArrayBuffer>;
nextInt(max?: number): number;
nextFloat1(): number;
}
+149
View File
@@ -0,0 +1,149 @@
import type { RNG } from './RNG.js';
// RNG 유틸리티 모음
export class RandUtil {
constructor(protected rng: RNG) {
}
public nextFloat1(): number {
return this.rng.nextFloat1();
}
public nextRange(min: number, max: number): number {
const range = max - min;
return this.nextFloat1() * (range) + min;
}
public nextRangeInt(min: number, max: number): number {
const range = max - min;
return this.rng.nextInt(range) + min;
}
public nextInt(max?: number): number {
return this.rng.nextInt(max);
}
public nextBit(): boolean {
const bits = this.rng.nextBits(1);
return bits[0]! != 0;
}
public nextBool(prob = 0.5): boolean {
if (prob >= 1) {
return true;
}
if (prob === 0.5) {
return this.nextBit();
}
if (prob <= 0) {
return false;
}
return this.nextFloat1() < prob;
}
public shuffle<T>(srcArray: T[]): T[] {
const cnt = srcArray.length;
if (cnt === 0) {
return [];
}
if (cnt > this.rng.getMaxInt()) {
throw 'Invalid random int range';
}
const result: T[] = Array.from(srcArray);
for (let srcIdx = 0; srcIdx < cnt; srcIdx += 1) {
const destIdx = this.rng.nextInt(cnt - srcIdx - 1) + srcIdx;
if (srcIdx === destIdx) {
continue;
}
const srcValue = result[srcIdx]!;
const destValue = result[destIdx]!;
result[srcIdx] = destValue;
result[destIdx] = srcValue;
}
return result;
}
//Object는 integer key에 예외가 있어 shuffleAssoc은 없음
public choice<T>(items: T[] | Record<string | number, T> | Set<T>): T {
if (items instanceof Array) {
if (items.length === 0) {
throw new Error('Empty items');
}
const idx = this.rng.nextInt(items.length - 1);
return items[idx]!;
}
if (items instanceof Set) {
return this.choice(Array.from(items.values()));
}
const key = this.choice(Array.from(Object.keys(items))) as keyof typeof items;
return items[key]!;
}
public choiceUsingWeight(items: Record<string | number, number>): string | number {
if (Object.keys(items).length === 0) {
throw new Error('Empty items');
}
let sum = 0;
for (const value of Object.values(items)) {
if (value <= 0) {
continue;
}
sum += value;
}
let rd = this.nextFloat1() * sum;
for (const [item, value] of Object.entries(items)) {
if (value <= 0) {
if (rd <= 0) {
return item;
}
continue;
}
if (rd <= value) {
return item;
}
rd -= value;
}
throw new Error('Unreacheable');
}
public choiceUsingWeightPair<T>(items: [T, number][]): T {
if (items.length === 0) {
throw new Error('Empty items');
}
let sum = 0;
for (const [, value] of items) {
if (value <= 0) {
continue;
}
sum += value;
}
let rd = this.nextFloat1() * sum;
for (const [item, value] of items) {
if (value <= 0) {
if (rd <= 0) {
return item;
}
continue;
}
if (rd <= value) {
return item;
}
rd -= value;
}
throw new Error('Unreacheable');
}
}
+284
View File
@@ -0,0 +1,284 @@
import type { RNG } from './RNG.js';
const maxSafeInt = Number.MAX_SAFE_INTEGER;
const clamp01 = (value: number): number => {
if (value < 0) {
return 0;
}
if (value > 1) {
return 1;
}
return value;
};
// 테스트에서 0/1만 고정으로 뽑기 위한 RNG
export class ConstantRNG implements RNG {
private readonly bit: 0 | 1;
public constructor(bit: 0 | 1) {
this.bit = bit;
}
public getMaxInt(): number {
return maxSafeInt;
}
public nextBytes(bytes: number): Uint8Array<ArrayBuffer> {
if (bytes <= 0) {
throw new Error('bytes must be positive');
}
const result = new Uint8Array(bytes);
result.fill(this.bit === 0 ? 0x00 : 0xff);
return result;
}
public nextBits(bits: number): Uint8Array<ArrayBuffer> {
if (bits <= 0) {
throw new Error('bits must be positive');
}
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
const result = this.nextBytes(bytes);
if (headBits === 0) {
return result;
}
result[bytes - 1]! &= 0xff >> (8 - headBits);
return result;
}
public nextInt(max?: number): number {
if (max === undefined || max === maxSafeInt) {
return this.bit === 0 ? 0 : maxSafeInt;
}
if (max > maxSafeInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
return this.bit === 0 ? 0 : max;
}
public nextFloat1(): number {
return this.bit;
}
}
// 중간값 고정 + bool은 0/1 교대로 뽑는 RNG
export class MidpointRNG implements RNG {
private bitState: 0 | 1;
public constructor(startBit: 0 | 1 = 0) {
this.bitState = startBit;
}
public getMaxInt(): number {
return maxSafeInt;
}
private nextBitRaw(): 0 | 1 {
const value = this.bitState;
this.bitState = value === 0 ? 1 : 0;
return value;
}
public nextBytes(bytes: number): Uint8Array<ArrayBuffer> {
if (bytes <= 0) {
throw new Error('bytes must be positive');
}
return this.nextBits(bytes * 8);
}
public nextBits(bits: number): Uint8Array<ArrayBuffer> {
if (bits <= 0) {
throw new Error('bits must be positive');
}
const bytes = (bits + 7) >> 3;
const result = new Uint8Array(bytes);
for (let bitIdx = 0; bitIdx < bits; bitIdx += 1) {
if (this.nextBitRaw() === 0) {
continue;
}
const byteIdx = bitIdx >> 3;
const offset = bitIdx & 0x7;
result[byteIdx]! |= 1 << offset;
}
return result;
}
public nextInt(max?: number): number {
if (max === undefined || max === maxSafeInt) {
return Math.floor(maxSafeInt / 2);
}
if (max > maxSafeInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
return Math.floor(max / 2);
}
public nextFloat1(): number {
return 0.5;
}
}
// 사인파 기반으로 주기/진폭을 조절하는 RNG
export class SineRNG implements RNG {
private step = 0;
private readonly period: number;
private readonly amplitude: number;
private readonly phase: number;
public constructor(period = 32, amplitude = 0.5, phase = 0) {
if (period <= 0) {
throw new Error('period must be positive');
}
this.period = period;
this.amplitude = amplitude;
this.phase = phase;
}
public getMaxInt(): number {
return maxSafeInt;
}
private nextWaveFloat(): number {
const radians = this.phase + (this.step * 2 * Math.PI) / this.period;
const value = 0.5 + this.amplitude * Math.sin(radians);
this.step += 1;
return clamp01(value);
}
public nextBytes(bytes: number): Uint8Array<ArrayBuffer> {
if (bytes <= 0) {
throw new Error('bytes must be positive');
}
const result = new Uint8Array(bytes);
for (let idx = 0; idx < bytes; idx += 1) {
const value = Math.floor(this.nextWaveFloat() * 256);
result[idx] = value >= 256 ? 255 : value;
}
return result;
}
public nextBits(bits: number): Uint8Array<ArrayBuffer> {
if (bits <= 0) {
throw new Error('bits must be positive');
}
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
const result = this.nextBytes(bytes);
if (headBits === 0) {
return result;
}
result[bytes - 1]! &= 0xff >> (8 - headBits);
return result;
}
public nextInt(max?: number): number {
if (max === undefined || max === maxSafeInt) {
const value = Math.floor(this.nextWaveFloat() * (maxSafeInt + 1));
return value > maxSafeInt ? maxSafeInt : value;
}
if (max > maxSafeInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
const value = Math.floor(this.nextWaveFloat() * (max + 1));
return value > max ? max : value;
}
public nextFloat1(): number {
return this.nextWaveFloat();
}
}
// 지정한 수열을 반복 재생하는 테스트용 RNG
export class SequenceRNG implements RNG {
private readonly sequence: number[];
private idx = 0;
public constructor(sequence: number[]) {
if (sequence.length === 0) {
throw new Error('sequence must not be empty');
}
this.sequence = sequence.map(clamp01);
}
public getMaxInt(): number {
return maxSafeInt;
}
private nextValue(): number {
const value = this.sequence[this.idx]!;
this.idx = (this.idx + 1) % this.sequence.length;
return value;
}
public nextBytes(bytes: number): Uint8Array<ArrayBuffer> {
if (bytes <= 0) {
throw new Error('bytes must be positive');
}
const result = new Uint8Array(bytes);
for (let idx = 0; idx < bytes; idx += 1) {
const value = Math.floor(this.nextValue() * 256);
result[idx] = value >= 256 ? 255 : value;
}
return result;
}
public nextBits(bits: number): Uint8Array<ArrayBuffer> {
if (bits <= 0) {
throw new Error('bits must be positive');
}
const bytes = (bits + 7) >> 3;
const headBits = bits & 0x7;
const result = this.nextBytes(bytes);
if (headBits === 0) {
return result;
}
result[bytes - 1]! &= 0xff >> (8 - headBits);
return result;
}
public nextInt(max?: number): number {
if (max === undefined || max === maxSafeInt) {
const value = Math.floor(this.nextValue() * (maxSafeInt + 1));
return value > maxSafeInt ? maxSafeInt : value;
}
if (max > maxSafeInt) {
throw new Error('Over max int');
}
if (max === 0) {
return 0;
}
if (max < 0) {
return -this.nextInt(-max);
}
const value = Math.floor(this.nextValue() * (max + 1));
return value > max ? max : value;
}
public nextFloat1(): number {
return this.nextValue();
}
}
@@ -0,0 +1,28 @@
import type { BytesLike } from './BytesLike.js';
export function convertBytesLikeToArrayBuffer(data: BytesLike, encodeUTF8 = true): ArrayBuffer {
if (data instanceof ArrayBuffer) {
return data;
}
if (data instanceof Uint8Array) {
if (
data.byteOffset === 0
&& data.byteLength === data.buffer.byteLength
&& data.buffer instanceof ArrayBuffer
) {
return data.buffer;
}
return data.slice().buffer;
}
if (data instanceof DataView) {
const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
return view.slice().buffer;
}
if (typeof (data) === 'string') {
if (encodeUTF8) {
return (new TextEncoder()).encode(data).buffer;
}
return new Uint8Array(data.split('').map((s) => s.codePointAt(0) as number)).buffer;
}
throw new Error('Unsupported BytesLike');
}
@@ -0,0 +1,30 @@
import type { BytesLike } from './BytesLike.js';
export function convertBytesLikeToUint8Array(
data: BytesLike,
encodeUTF8 = true
): Uint8Array<ArrayBuffer> {
if (data instanceof Uint8Array) {
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) {
return new Uint8Array<ArrayBuffer>(data.buffer, data.byteOffset, data.byteLength);
}
if (typeof (data) === 'string') {
if (encodeUTF8) {
return (new TextEncoder()).encode(data);
}
return new Uint8Array(data.split('').map((s) => s.codePointAt(0) as number));
}
throw new Error('Unsupported BytesLike');
}