@ddunigma/node 1.1.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,9 @@ import { BaseDdu } from "../base/BaseDdu";
2
2
  import { DduSetSymbol, dduDefaultConstructorOptions, } from "../types";
3
3
  import { getCharSet } from "../charSets";
4
4
  export class Ddu64 extends BaseDdu {
5
+ // =========================================================================================
6
+ // Properties
7
+ // =========================================================================================
5
8
  dduChar;
6
9
  paddingChar;
7
10
  charLength;
@@ -12,310 +15,460 @@ export class Ddu64 extends BaseDdu {
12
15
  isPredefinedCharSet;
13
16
  effectiveBitLength;
14
17
  maxBinaryValue;
15
- binaryChunkToIntFn;
16
- indexToBinaryCache;
18
+ // =========================================================================================
19
+ // Constructor
20
+ // =========================================================================================
17
21
  constructor(dduChar, paddingChar, dduOptions) {
18
22
  super();
19
- const shouldThrowError = dduOptions?.useBuildErrorReturn ?? false;
20
- const getCharSetFromSymbol = (symbol) => {
21
- const cs = getCharSet(symbol);
22
- if (!cs)
23
- throw new Error(`CharSet with symbol ${symbol} not found`);
24
- return cs;
25
- };
26
- // charset 초기화
27
- let charSet, padding, requiredLength, bitLength, isPredefined;
28
- try {
29
- const finalDduChar = dduChar ?? dduOptions?.dduChar;
30
- const finalPadding = paddingChar ?? dduOptions?.paddingChar;
31
- if (finalDduChar) {
32
- // 커스텀 charset
33
- if (!finalPadding) {
34
- throw new Error(`[Ddu64 Constructor] paddingChar is required when dduChar is provided. Received: dduChar=${typeof finalDduChar}, paddingChar=${finalPadding}`);
35
- }
36
- // 문자열을 배열로 변환 (중복 제거 없이)
37
- const arr = typeof finalDduChar === "string" ? [...finalDduChar.trim()] : finalDduChar;
38
- // 중복 검사 (useBuildErrorReturn이 true일 때만)
39
- if (shouldThrowError) {
40
- const uniqueChars = new Set(arr);
41
- if (uniqueChars.size !== arr.length) {
42
- const duplicates = arr.filter((char, index) => arr.indexOf(char) !== index);
43
- throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters. Total: ${arr.length}, Unique: ${uniqueChars.size}, Duplicates: [${[...new Set(duplicates)].join(', ')}]`);
44
- }
45
- }
46
- const len = dduOptions?.requiredLength ?? arr.length;
47
- if (arr.length < len) {
48
- throw new Error(`[Ddu64 Constructor] Insufficient characters in charset. Required: ${len}, Provided: ${arr.length}`);
49
- }
50
- const usePow2 = dduOptions?.usePowerOfTwo === true || (dduOptions?.usePowerOfTwo === undefined && len > 0 && (len & (len - 1)) === 0);
51
- if (usePow2) {
52
- const exp = this.getLargestPowerOfTwoExponent(len);
53
- const pow2Len = 1 << exp;
54
- [charSet, padding, requiredLength, bitLength, isPredefined] = [arr.slice(0, pow2Len), finalPadding, pow2Len, exp, false];
55
- }
56
- else {
57
- [charSet, padding, requiredLength, bitLength, isPredefined] = [arr.slice(0, len), finalPadding, len, this.getBitLength(len), false];
58
- }
59
- }
60
- else if (dduOptions?.dduSetSymbol) {
61
- // 미리 정의된 charset
62
- const cs = getCharSetFromSymbol(dduOptions.dduSetSymbol);
63
- const usePow2 = dduOptions?.usePowerOfTwo === true || (dduOptions?.usePowerOfTwo === undefined && cs.maxRequiredLength > 0 && (cs.maxRequiredLength & (cs.maxRequiredLength - 1)) === 0);
64
- if (usePow2) {
65
- const exp = this.getLargestPowerOfTwoExponent(cs.maxRequiredLength);
66
- const pow2Len = 1 << exp;
67
- [charSet, padding, requiredLength, bitLength, isPredefined] = [cs.charSet.slice(0, pow2Len), cs.paddingChar, pow2Len, exp, true];
68
- }
69
- else {
70
- [charSet, padding, requiredLength, bitLength, isPredefined] = [cs.charSet, cs.paddingChar, cs.maxRequiredLength, cs.bitLength, true];
71
- }
72
- }
73
- else {
74
- // 기본 charset
75
- const cs = getCharSetFromSymbol(dduDefaultConstructorOptions.dduSetSymbol ?? DduSetSymbol.DDU);
76
- [charSet, padding, requiredLength, bitLength, isPredefined] = [cs.charSet, cs.paddingChar, cs.maxRequiredLength, cs.bitLength, true];
77
- }
78
- }
79
- catch (error) {
80
- if (shouldThrowError)
81
- throw error;
82
- // fallback
83
- const fallbackSymbol = dduOptions?.dduSetSymbol ?? dduDefaultConstructorOptions.dduSetSymbol ?? DduSetSymbol.ONECHARSET;
84
- const cs = getCharSet(fallbackSymbol) ?? getCharSet(DduSetSymbol.ONECHARSET);
85
- if (!cs)
86
- throw new Error(`Critical: No fallback CharSet available`);
87
- [charSet, padding, requiredLength, bitLength, isPredefined] = [cs.charSet, cs.paddingChar, cs.maxRequiredLength, cs.bitLength, true];
88
- }
89
- // 정규화 및 검증
90
- const normalized = this.normalizeCharSet(charSet, padding, requiredLength, bitLength, isPredefined, shouldThrowError, dduOptions);
23
+ const shouldThrow = dduOptions?.useBuildErrorReturn ?? false;
24
+ // 1. CharSet 초기화 검증
25
+ const initial = this.resolveInitialCharSet(dduChar, paddingChar, dduOptions, shouldThrow);
26
+ const normalized = this.normalizeCharSet(initial, shouldThrow, dduOptions);
91
27
  this.dduChar = normalized.charSet;
92
28
  this.paddingChar = normalized.padding;
93
29
  this.charLength = normalized.charLength;
94
30
  this.isPredefinedCharSet = normalized.isPredefined;
95
31
  this.encoding = dduOptions?.encoding ?? this.defaultEncoding;
32
+ // 2. 비트 연산 상수 계산
96
33
  const dduLength = this.dduChar.length;
97
- const recalculatedBitLength = this.getBitLength(dduLength);
98
34
  this.usePowerOfTwo = dduLength > 0 && (dduLength & (dduLength - 1)) === 0;
99
- this.bitLength = this.usePowerOfTwo
100
- ? this.getLargestPowerOfTwoExponent(dduLength)
101
- : recalculatedBitLength;
102
- this.effectiveBitLength = this.usePowerOfTwo ? this.bitLength : recalculatedBitLength;
35
+ const computedBitLength = this.getBitLength(dduLength);
36
+ this.bitLength = this.usePowerOfTwo ? this.getLargestPowerOfTwoExponent(dduLength) : computedBitLength;
37
+ this.effectiveBitLength = this.usePowerOfTwo ? this.bitLength : computedBitLength;
103
38
  this.maxBinaryValue = 2 ** this.effectiveBitLength;
104
- // 성능 최적화: 단일 구현 사용 (벤치마크 결과 Method2가 더 빠르고 안정적)
105
- // Method2는 32비트 이상에서도 오버플로우 없이 정확한 결과 제공
106
- this.binaryChunkToIntFn = (chunk) => chunk.split('').reduce((v, c) => v * 2 + (c.charCodeAt(0) & 1), 0);
107
- this.dduChar.forEach((char, index) => this.dduBinaryLookup.set(char, index));
39
+ // 3. Lookup Table 생성 (Decoding용)
40
+ for (let i = 0; i < dduLength; i++) {
41
+ this.dduBinaryLookup.set(this.dduChar[i], i);
42
+ }
43
+ // 4. 안전성 검사
108
44
  if (this.charLength === 1 && !this.isPredefinedCharSet) {
109
45
  this.validateCombinationDuplicates(this.dduChar, this.paddingChar, dduLength);
110
46
  }
111
- if (this.effectiveBitLength <= 16) {
112
- this.indexToBinaryCache = Array.from({ length: this.maxBinaryValue }, (_, i) => i.toString(2).padStart(this.effectiveBitLength, "0"));
47
+ }
48
+ // =========================================================================================
49
+ // Public API
50
+ // =========================================================================================
51
+ /**
52
+ * 데이터를 DDU 포맷으로 인코딩합니다.
53
+ * 성능을 위해 24비트 이하는 Fast Path(number 연산)를 사용합니다.
54
+ */
55
+ encode(input, _options) {
56
+ const bufferInput = typeof input === "string" ? Buffer.from(input, this.encoding) : input;
57
+ if (this.effectiveBitLength <= 24) {
58
+ return this.encodeFast(bufferInput);
113
59
  }
114
- else {
115
- this.indexToBinaryCache = null;
60
+ return this.encodeBigInt(bufferInput);
61
+ }
62
+ /**
63
+ * DDU 포맷 문자열을 버퍼로 디코딩합니다.
64
+ */
65
+ decodeToBuffer(input, _options) {
66
+ if (this.effectiveBitLength <= 24) {
67
+ return this.decodeFast(input);
116
68
  }
69
+ return this.decodeBigInt(input);
117
70
  }
118
- normalizeCharSet(charSet, padding, requiredLength, bitLength, isPredefined, shouldThrowError, dduOptions) {
119
- const applyFallback = () => {
120
- const fallbackSymbol = dduOptions?.dduSetSymbol ?? dduDefaultConstructorOptions.dduSetSymbol ?? DduSetSymbol.ONECHARSET;
121
- const cs = getCharSet(fallbackSymbol) ?? getCharSet(DduSetSymbol.ONECHARSET);
122
- if (!cs)
123
- throw new Error(`Critical: No fallback CharSet available`);
124
- return { charSet: cs.charSet, padding: cs.paddingChar, requiredLength: cs.maxRequiredLength, bitLength: cs.bitLength, isPredefined: true };
125
- };
126
- const validate = (condition, message) => {
127
- if (condition) {
128
- if (shouldThrowError)
129
- throw new Error(message);
130
- const fb = applyFallback();
131
- [charSet, padding, requiredLength, bitLength, isPredefined] = [fb.charSet, fb.padding, fb.requiredLength, fb.bitLength, fb.isPredefined];
132
- return true;
133
- }
134
- return false;
71
+ decode(input, _options) {
72
+ return this.decodeToBuffer(input, _options).toString(this.encoding);
73
+ }
74
+ getCharSetInfo() {
75
+ return {
76
+ charSet: [...this.dduChar],
77
+ paddingChar: this.paddingChar,
78
+ charLength: this.charLength,
79
+ bitLength: this.bitLength,
80
+ usePowerOfTwo: this.usePowerOfTwo,
81
+ encoding: this.encoding,
135
82
  };
136
- // 중복 제거 (모든 charset에 적용)
137
- const uniqueChars = new Set(charSet);
138
- if (uniqueChars.size !== charSet.length) {
139
- const duplicates = charSet.filter((char, index) => charSet.indexOf(char) !== index);
140
- const errorMsg = `[Ddu64 normalizeCharSet] Character set contains duplicate characters. Total: ${charSet.length}, Unique: ${uniqueChars.size}, Duplicates: [${[...new Set(duplicates)].join(', ')}]`;
141
- if (shouldThrowError)
142
- throw new Error(errorMsg);
143
- // 중복 제거 계속 진행
144
- charSet = Array.from(uniqueChars);
145
- if (!isPredefined) {
146
- requiredLength = charSet.length;
83
+ }
84
+ // =========================================================================================
85
+ // Fast Engine (Optimized for Speed)
86
+ // Uses standard JS numbers (safe up to ~24 bits per chunk) to avoid BigInt GC overhead.
87
+ // =========================================================================================
88
+ encodeFast(bufferInput) {
89
+ const resultParts = [];
90
+ const { dduChar, effectiveBitLength: bitLength, paddingChar } = this;
91
+ const dduLength = dduChar.length;
92
+ let accumulator = 0;
93
+ let accumulatorBits = 0;
94
+ // Loop Unswitching: 조건문을 루프 밖으로 빼서 CPU 분기 예측 효율 향상
95
+ if (this.usePowerOfTwo) {
96
+ for (const byte of bufferInput) {
97
+ accumulator = (accumulator << 8) | byte;
98
+ accumulatorBits += 8;
99
+ while (accumulatorBits >= bitLength) {
100
+ const shift = accumulatorBits - bitLength;
101
+ const index = accumulator >> shift;
102
+ resultParts.push(dduChar[index]);
103
+ accumulatorBits -= bitLength;
104
+ accumulator &= (1 << accumulatorBits) - 1;
105
+ }
147
106
  }
148
107
  }
149
- // 검증
150
- if (validate(charSet.length < requiredLength, `[Ddu64 normalizeCharSet] Insufficient characters. Required: ${requiredLength}, Provided: ${charSet.length}`)) {
151
- return this.normalizeCharSet(charSet, padding, requiredLength, bitLength, isPredefined, shouldThrowError, dduOptions);
152
- }
153
- if (validate(requiredLength < 2, `[Ddu64 normalizeCharSet] At least 2 unique characters are required. Provided: ${requiredLength}`)) {
154
- return this.normalizeCharSet(charSet, padding, requiredLength, bitLength, isPredefined, shouldThrowError, dduOptions);
155
- }
156
- if (validate(bitLength <= 0, `[Ddu64 normalizeCharSet] Invalid bit length (${bitLength}) for charset size ${requiredLength}`)) {
157
- return this.normalizeCharSet(charSet, padding, requiredLength, bitLength, isPredefined, shouldThrowError, dduOptions);
158
- }
159
- let charLength = charSet[0]?.length ?? 0;
160
- validate(charLength === 0, `[Ddu64 normalizeCharSet] Empty charset. Required: ${requiredLength} characters`);
161
- const invalidIndex = charSet.findIndex(char => char.length !== charLength);
162
- if (invalidIndex !== -1) {
163
- if (shouldThrowError) {
164
- throw new Error(`[Ddu64 normalizeCharSet] Inconsistent character length. Expected: ${charLength}, but character at index ${invalidIndex} ("${charSet[invalidIndex]}") has length ${charSet[invalidIndex].length}`);
108
+ else {
109
+ for (const byte of bufferInput) {
110
+ accumulator = (accumulator << 8) | byte;
111
+ accumulatorBits += 8;
112
+ while (accumulatorBits >= bitLength) {
113
+ const shift = accumulatorBits - bitLength;
114
+ const index = accumulator >> shift;
115
+ // 2의 제곱수는 나눗셈으로 인덱스 계산
116
+ const div = (index / dduLength) | 0;
117
+ const mod = index % dduLength;
118
+ resultParts.push(dduChar[div] + dduChar[mod]);
119
+ accumulatorBits -= bitLength;
120
+ accumulator &= (1 << accumulatorBits) - 1;
121
+ }
165
122
  }
166
- charSet = charSet.filter(char => char.length === charLength);
167
- validate(charSet.length < requiredLength, `[Ddu64 normalizeCharSet] Insufficient characters after filtering. Required: ${requiredLength}, Remaining: ${charSet.length}`);
168
- charLength = charSet[0]?.length ?? 0;
169
123
  }
170
- validate(!charSet.length, `[Ddu64 normalizeCharSet] Empty charset after validation`);
171
- validate(padding.length !== charLength, `[Ddu64 normalizeCharSet] Padding character length mismatch. Expected: ${charLength}, Got: ${padding.length} (padding: "${padding}")`);
172
- if (new Set(charSet).has(padding)) {
173
- if (shouldThrowError) {
174
- throw new Error(`[Ddu64 normalizeCharSet] Padding character "${padding}" conflicts with charset. Padding must not be in the character set.`);
124
+ // 남은 비트 패딩 처리
125
+ if (accumulatorBits > 0) {
126
+ const paddingBits = bitLength - accumulatorBits;
127
+ const index = accumulator << paddingBits;
128
+ if (this.usePowerOfTwo) {
129
+ resultParts.push(dduChar[index]);
175
130
  }
176
- charSet = charSet.filter(char => char !== padding);
177
- validate(charSet.length < requiredLength, `[Ddu64 normalizeCharSet] Insufficient characters after removing padding conflict. Required: ${requiredLength}, Remaining: ${charSet.length}`);
178
- charLength = charSet[0]?.length ?? 0;
179
- }
180
- return { charSet: charSet.slice(0, requiredLength), padding, requiredLength, bitLength, isPredefined, charLength };
181
- }
182
- getBinaryFromIndex(index) {
183
- if (index < 0 || index >= this.maxBinaryValue) {
184
- throw new Error(`[Ddu64] Binary index overflow. Received: ${index}, Allowed range: 0-${this.maxBinaryValue - 1}`);
131
+ else {
132
+ const div = (index / dduLength) | 0;
133
+ const mod = index % dduLength;
134
+ resultParts.push(dduChar[div] + dduChar[mod]);
135
+ }
136
+ return resultParts.join("") + paddingChar + paddingBits.toString();
185
137
  }
186
- return this.indexToBinaryCache?.[index] ?? index.toString(2).padStart(this.effectiveBitLength, "0");
138
+ return resultParts.join("");
187
139
  }
188
- validateCombinationDuplicates(charSet, paddingChar, requiredLength) {
189
- const charLength = charSet[0].length;
190
- // 조합 충돌 검사는 단일 문자 집합이면서 비교적 작은 경우(<=256)에만 적용한다.
191
- if (charLength !== 1 || requiredLength > 256) {
192
- return;
193
- }
194
- const allStrings = new Set([...charSet.slice(0, requiredLength), paddingChar]);
195
- const limit = Math.min(charSet.length, requiredLength);
196
- for (let i = 0; i < limit; i++) {
197
- for (let j = 0; j < limit; j++) {
198
- const combo = charSet[i] + charSet[j];
199
- if (allStrings.has(combo)) {
200
- throw new Error(`Combination conflict: "${charSet[i]}" + "${charSet[j]}" = "${combo}" already exists`);
140
+ decodeFast(input) {
141
+ const { cleanedInput, paddingBits } = this.parsePaddingAndGetInput(input);
142
+ const inputLen = cleanedInput.length;
143
+ const buffer = [];
144
+ let accumulator = 0;
145
+ let accumulatorBits = 0;
146
+ const { effectiveBitLength: bitLength, dduBinaryLookup: lookup, charLength, maxBinaryValue } = this;
147
+ const dduLength = this.dduChar.length;
148
+ if (this.usePowerOfTwo) {
149
+ const chunkSize = charLength;
150
+ for (let i = 0; i < inputLen; i += chunkSize) {
151
+ const chunk = cleanedInput.slice(i, i + charLength);
152
+ const val = lookup.get(chunk);
153
+ if (val === undefined)
154
+ throw new Error(`[Ddu64 decode] Invalid character "${chunk}" at ${i}`);
155
+ if (val >= maxBinaryValue)
156
+ throw new Error(`[Ddu64 decode] Value ${val} exceeds range`);
157
+ accumulator = (accumulator << bitLength) | val;
158
+ accumulatorBits += bitLength;
159
+ // 마지막 청크 패딩 비트 제거
160
+ if (i + chunkSize >= inputLen && paddingBits > 0) {
161
+ accumulator >>= paddingBits;
162
+ accumulatorBits -= paddingBits;
163
+ }
164
+ while (accumulatorBits >= 8) {
165
+ const shift = accumulatorBits - 8;
166
+ buffer.push((accumulator >> shift) & 0xFF);
167
+ accumulatorBits -= 8;
168
+ accumulator &= (1 << accumulatorBits) - 1;
201
169
  }
202
170
  }
203
- const charPad = charSet[i] + paddingChar;
204
- const padChar = paddingChar + charSet[i];
205
- if (allStrings.has(charPad)) {
206
- throw new Error(`Combination conflict: "${charSet[i]}" + padding "${paddingChar}" = "${charPad}"`);
171
+ }
172
+ else {
173
+ const chunkSize = charLength * 2;
174
+ for (let i = 0; i < inputLen; i += chunkSize) {
175
+ const c1 = cleanedInput.slice(i, i + charLength);
176
+ const c2 = cleanedInput.slice(i + charLength, i + chunkSize);
177
+ const v1 = lookup.get(c1);
178
+ const v2 = lookup.get(c2);
179
+ if (v1 === undefined)
180
+ throw new Error(`[Ddu64 decode] Invalid character "${c1}" at ${i}`);
181
+ if (v2 === undefined)
182
+ throw new Error(`[Ddu64 decode] Invalid character "${c2}" at ${i + charLength}`);
183
+ const value = v1 * dduLength + v2;
184
+ if (value >= maxBinaryValue)
185
+ throw new Error(`[Ddu64 decode] Value ${value} exceeds range`);
186
+ accumulator = (accumulator << bitLength) | value;
187
+ accumulatorBits += bitLength;
188
+ if (i + chunkSize >= inputLen && paddingBits > 0) {
189
+ accumulator >>= paddingBits;
190
+ accumulatorBits -= paddingBits;
191
+ }
192
+ while (accumulatorBits >= 8) {
193
+ const shift = accumulatorBits - 8;
194
+ buffer.push((accumulator >> shift) & 0xFF);
195
+ accumulatorBits -= 8;
196
+ accumulator &= (1 << accumulatorBits) - 1;
197
+ }
207
198
  }
208
- if (allStrings.has(padChar)) {
209
- throw new Error(`Combination conflict: padding "${paddingChar}" + "${charSet[i]}" = "${padChar}"`);
199
+ }
200
+ return Buffer.from(buffer);
201
+ }
202
+ // =========================================================================================
203
+ // Safe Engine (BigInt)
204
+ // Fallback for huge charsets (> 24 bits per chunk) where 32-bit integers overflow.
205
+ // =========================================================================================
206
+ encodeBigInt(bufferInput) {
207
+ const resultParts = [];
208
+ const { dduChar, effectiveBitLength: bitLength } = this;
209
+ const dduLength = dduChar.length;
210
+ const bigBitLength = BigInt(bitLength);
211
+ let accumulator = 0n;
212
+ let accumulatorBits = 0;
213
+ if (this.usePowerOfTwo) {
214
+ for (const byte of bufferInput) {
215
+ accumulator = (accumulator << 8n) | BigInt(byte);
216
+ accumulatorBits += 8;
217
+ while (accumulatorBits >= bitLength) {
218
+ const shift = accumulatorBits - bitLength;
219
+ const value = accumulator >> BigInt(shift);
220
+ resultParts.push(dduChar[Number(value)]);
221
+ accumulator &= ((1n << BigInt(shift)) - 1n);
222
+ accumulatorBits -= bitLength;
223
+ }
210
224
  }
211
225
  }
212
- const doublePad = paddingChar + paddingChar;
213
- if (allStrings.has(doublePad)) {
214
- throw new Error(`Combination conflict: double padding "${doublePad}" already exists`);
226
+ else {
227
+ for (const byte of bufferInput) {
228
+ accumulator = (accumulator << 8n) | BigInt(byte);
229
+ accumulatorBits += 8;
230
+ while (accumulatorBits >= bitLength) {
231
+ const shift = accumulatorBits - bitLength;
232
+ const value = accumulator >> BigInt(shift);
233
+ const idx = Number(value);
234
+ resultParts.push(dduChar[Math.floor(idx / dduLength)] + dduChar[idx % dduLength]);
235
+ accumulator &= ((1n << BigInt(shift)) - 1n);
236
+ accumulatorBits -= bitLength;
237
+ }
238
+ }
215
239
  }
216
- }
217
- encode(input, _options) {
218
- // options는 구버전 호환성을 위해 유지하지만 사용하지 않음
219
- const bufferInput = typeof input === "string" ? Buffer.from(input, this.encoding) : input;
220
- // 생성자에서 설정된 값 사용
221
- const dduLength = this.dduChar.length;
222
- const effectiveBitLength = this.effectiveBitLength;
223
- const { dduBinary, padding } = this.bufferToDduBinary(bufferInput, effectiveBitLength);
224
- // 문자열 연결 최적화: Array + join 사용
225
- const resultParts = new Array(dduBinary.length);
226
- // 각 비트 청크를 변환
227
- for (let i = 0; i < dduBinary.length; i++) {
228
- const binaryChunk = dduBinary[i];
229
- const charInt = this.binaryChunkToIntFn(binaryChunk);
230
- if (!this.usePowerOfTwo) {
231
- // 가변 길이 조합 인코딩 (멀티바이트 문자도 지원)
232
- const quotient = Math.floor(charInt / dduLength);
233
- const remainder = charInt % dduLength;
234
- resultParts[i] = this.dduChar[quotient] + this.dduChar[remainder];
240
+ if (accumulatorBits > 0) {
241
+ const paddingBits = bitLength - accumulatorBits;
242
+ const index = Number(accumulator << BigInt(paddingBits));
243
+ if (this.usePowerOfTwo) {
244
+ resultParts.push(dduChar[index]);
235
245
  }
236
246
  else {
237
- // 고정 길이 직접 매핑
238
- resultParts[i] = this.dduChar[charInt];
247
+ resultParts.push(dduChar[Math.floor(index / dduLength)] + dduChar[index % dduLength]);
239
248
  }
249
+ return resultParts.join("") + this.paddingChar + paddingBits.toString();
240
250
  }
241
- let resultString = resultParts.join("");
242
- // 패딩 비트 정보를 padChar + 패딩비트수 형태로 추가
243
- if (padding > 0) {
244
- resultString += this.paddingChar + padding;
245
- }
246
- return resultString;
251
+ return resultParts.join("");
247
252
  }
248
- decodeToBuffer(input, _options) {
249
- let paddingBits = 0;
250
- if (input.length >= this.paddingChar.length) {
251
- const padCharIndex = input.lastIndexOf(this.paddingChar);
252
- if (padCharIndex >= 0 &&
253
- padCharIndex % this.charLength === 0 &&
254
- padCharIndex + this.paddingChar.length <= input.length) {
255
- const paddingSection = input.slice(padCharIndex + this.paddingChar.length);
256
- if (paddingSection.length === 0) {
257
- throw new Error(`[Ddu64 decode] Invalid padding format. Missing padding length after "${this.paddingChar}"`);
258
- }
259
- paddingBits = parseInt(paddingSection, 10);
260
- if (isNaN(paddingBits) ||
261
- paddingSection !== paddingBits.toString() ||
262
- paddingBits < 0 ||
263
- paddingBits >= this.effectiveBitLength) {
264
- throw new Error(`[Ddu64 decode] Invalid padding format. Expected integer between 0 and ${this.effectiveBitLength - 1}, Got: "${paddingSection}"`);
265
- }
266
- input = input.substring(0, padCharIndex);
267
- }
268
- }
269
- let dduBinary = "";
253
+ decodeBigInt(input) {
254
+ const { cleanedInput, paddingBits } = this.parsePaddingAndGetInput(input);
255
+ const buffer = [];
256
+ let accumulator = 0n;
257
+ let accumulatorBits = 0;
258
+ const { effectiveBitLength: bitLength, dduBinaryLookup: lookup } = this;
259
+ const bigBitLength = BigInt(bitLength);
270
260
  const dduLength = this.dduChar.length;
271
- if (!this.usePowerOfTwo) {
272
- const chunkSize = this.charLength * 2;
273
- for (let i = 0; i < input.length; i += chunkSize) {
274
- const firstChar = input.slice(i, i + this.charLength);
275
- const secondChar = input.slice(i + this.charLength, i + chunkSize);
276
- const firstIndex = this.dduBinaryLookup.get(firstChar);
277
- const secondIndex = this.dduBinaryLookup.get(secondChar);
278
- if (firstIndex === undefined || secondIndex === undefined) {
279
- const invalidChar = firstIndex === undefined ? firstChar : secondChar;
280
- throw new Error(`[Ddu64 decode] Invalid character in encoded string. Character: "${invalidChar}", Position: ${i}, Expected charset size: ${dduLength}`);
261
+ const chunkSize = this.usePowerOfTwo ? this.charLength : this.charLength * 2;
262
+ if (this.usePowerOfTwo) {
263
+ for (let i = 0; i < cleanedInput.length; i += chunkSize) {
264
+ const chunk = cleanedInput.slice(i, i + this.charLength);
265
+ const val = lookup.get(chunk);
266
+ if (val === undefined)
267
+ throw new Error(`[Ddu64 decode] Invalid character "${chunk}" at ${i}`);
268
+ accumulator = (accumulator << bigBitLength) | BigInt(val);
269
+ accumulatorBits += bitLength;
270
+ if (i + chunkSize >= cleanedInput.length && paddingBits > 0) {
271
+ accumulator >>= BigInt(paddingBits);
272
+ accumulatorBits -= paddingBits;
281
273
  }
282
- const value = firstIndex * dduLength + secondIndex;
283
- if (value >= this.maxBinaryValue) {
284
- throw new Error(`[Ddu64 decode] Invalid character combination detected. Calculated value ${value} exceeds binary range ${this.maxBinaryValue - 1}.`);
274
+ while (accumulatorBits >= 8) {
275
+ const shift = accumulatorBits - 8;
276
+ buffer.push(Number((accumulator >> BigInt(shift)) & 0xffn));
277
+ accumulator &= ((1n << BigInt(shift)) - 1n);
278
+ accumulatorBits -= 8;
285
279
  }
286
- dduBinary += this.getBinaryFromIndex(value);
287
280
  }
288
281
  }
289
282
  else {
290
- for (let i = 0; i < input.length; i += this.charLength) {
291
- const charChunk = input.slice(i, i + this.charLength);
292
- const charIndex = this.dduBinaryLookup.get(charChunk);
293
- if (charIndex === undefined) {
294
- throw new Error(`[Ddu64 decode] Invalid character in encoded string. Character: "${charChunk}", Position: ${i}, Charset size: ${dduLength}, Character length: ${this.charLength}`);
283
+ for (let i = 0; i < cleanedInput.length; i += chunkSize) {
284
+ const c1 = cleanedInput.slice(i, i + this.charLength);
285
+ const c2 = cleanedInput.slice(i + this.charLength, i + chunkSize);
286
+ const v1 = lookup.get(c1);
287
+ const v2 = lookup.get(c2);
288
+ if (v1 === undefined)
289
+ throw new Error(`[Ddu64 decode] Invalid character "${c1}" at ${i}`);
290
+ if (v2 === undefined)
291
+ throw new Error(`[Ddu64 decode] Invalid character "${c2}" at ${i + this.charLength}`);
292
+ const value = v1 * dduLength + v2;
293
+ if (value >= this.maxBinaryValue)
294
+ throw new Error(`[Ddu64 decode] Value ${value} exceeds range`);
295
+ accumulator = (accumulator << bigBitLength) | BigInt(value);
296
+ accumulatorBits += bitLength;
297
+ if (i + chunkSize >= cleanedInput.length && paddingBits > 0) {
298
+ accumulator >>= BigInt(paddingBits);
299
+ accumulatorBits -= paddingBits;
295
300
  }
296
- if (charIndex >= this.maxBinaryValue) {
297
- throw new Error(`[Ddu64 decode] Invalid binary index ${charIndex}. Allowed range: 0-${this.maxBinaryValue - 1}`);
301
+ while (accumulatorBits >= 8) {
302
+ const shift = accumulatorBits - 8;
303
+ buffer.push(Number((accumulator >> BigInt(shift)) & 0xffn));
304
+ accumulator &= ((1n << BigInt(shift)) - 1n);
305
+ accumulatorBits -= 8;
298
306
  }
299
- dduBinary += this.getBinaryFromIndex(charIndex);
300
307
  }
301
308
  }
302
- return this.dduBinaryToBuffer(dduBinary, paddingBits);
309
+ return Buffer.from(buffer);
303
310
  }
304
- decode(input, _options) {
305
- return this.decodeToBuffer(input, _options).toString(this.encoding);
311
+ // =========================================================================================
312
+ // Internal Helpers (Normalization & Validation)
313
+ // =========================================================================================
314
+ parsePaddingAndGetInput(input) {
315
+ const padLen = this.paddingChar.length;
316
+ if (input.length < padLen)
317
+ return { cleanedInput: input, paddingBits: 0 };
318
+ const padIdx = input.lastIndexOf(this.paddingChar);
319
+ // 패딩 문자가 존재하고, 위치가 올바른지(chunk 단위) 확인
320
+ if (padIdx >= 0 && padIdx % this.charLength === 0 && padIdx + padLen <= input.length) {
321
+ const paddingSection = input.slice(padIdx + padLen);
322
+ if (!paddingSection)
323
+ throw new Error(`[Ddu64 decode] Invalid padding format. Missing padding length`);
324
+ const paddingBits = parseInt(paddingSection, 10);
325
+ if (isNaN(paddingBits) || paddingSection !== paddingBits.toString() || paddingBits < 0 || paddingBits >= this.effectiveBitLength) {
326
+ throw new Error(`[Ddu64 decode] Invalid padding format. Got: "${paddingSection}"`);
327
+ }
328
+ return { cleanedInput: input.substring(0, padIdx), paddingBits };
329
+ }
330
+ return { cleanedInput: input, paddingBits: 0 };
306
331
  }
307
332
  /**
308
- * 테스트 디버깅용 getter 메서드
309
- * 인코더의 내부 상태 정보를 반환
333
+ * 입력된 CharSet을 검증하고 정리(Normalization)합니다.
334
+ * 문제가 발생하면 옵션에 따라 Error를 던지거나 Fallback CharSet을 반환합니다.
310
335
  */
311
- getCharSetInfo() {
312
- return {
313
- charSet: [...this.dduChar],
314
- paddingChar: this.paddingChar,
315
- charLength: this.charLength,
316
- bitLength: this.bitLength,
317
- usePowerOfTwo: this.usePowerOfTwo,
318
- encoding: this.encoding,
336
+ normalizeCharSet(current, shouldThrow, dduOptions) {
337
+ let state = { ...current };
338
+ // 재시도 루프 (Fallback 로직 포함)
339
+ while (true) {
340
+ try {
341
+ // 1. 중복 제거
342
+ const uniqueChars = Array.from(new Set(state.charSet));
343
+ if (uniqueChars.length !== state.charSet.length) {
344
+ if (shouldThrow) {
345
+ const duplicates = state.charSet.filter((c, i) => state.charSet.indexOf(c) !== i);
346
+ throw new Error(`[Ddu64 normalizeCharSet] Character set contains duplicate characters: [${[...new Set(duplicates)].join(", ")}]`);
347
+ }
348
+ state.charSet = uniqueChars;
349
+ if (!state.isPredefined)
350
+ state.requiredLength = state.charSet.length;
351
+ }
352
+ // 2. 기본 조건 검사
353
+ if (state.charSet.length < state.requiredLength)
354
+ throw new Error(`[Ddu64 normalizeCharSet] Insufficient characters. Required: ${state.requiredLength}, Has: ${state.charSet.length}`);
355
+ if (state.requiredLength < 2)
356
+ throw new Error(`[Ddu64 normalizeCharSet] At least 2 unique characters required.`);
357
+ if (state.charSet.length === 0)
358
+ throw new Error(`[Ddu64 normalizeCharSet] Empty charset.`);
359
+ // 3. 문자 길이 일관성 검사
360
+ const charLength = state.charSet[0].length;
361
+ const invalidChar = state.charSet.find(c => c.length !== charLength);
362
+ if (invalidChar) {
363
+ if (shouldThrow)
364
+ throw new Error(`[Ddu64 normalizeCharSet] Inconsistent char length. Expected ${charLength}, found "${invalidChar}" (${invalidChar.length})`);
365
+ // 필터링 후 재검증을 위해 예외 발생시켜 Fallback 또는 재시도 유도
366
+ throw new Error("Filtered inconsistent chars (internal retry)");
367
+ }
368
+ // 4. 패딩 충돌 검사
369
+ if (state.padding.length !== charLength)
370
+ throw new Error(`[Ddu64 normalizeCharSet] Padding length mismatch. Expected ${charLength}, got ${state.padding.length}`);
371
+ if (state.charSet.includes(state.padding)) {
372
+ if (shouldThrow)
373
+ throw new Error(`[Ddu64 normalizeCharSet] Padding character "${state.padding}" conflicts with charset.`);
374
+ state.charSet = state.charSet.filter(c => c !== state.padding);
375
+ }
376
+ return {
377
+ charSet: state.charSet.slice(0, state.requiredLength),
378
+ padding: state.padding,
379
+ charLength,
380
+ isPredefined: state.isPredefined,
381
+ };
382
+ }
383
+ catch (e) {
384
+ // 사용자가 명시적으로 에러를 요청했거나, 복구 불가능한 에러인 경우
385
+ if (shouldThrow && !e.message.includes("internal retry"))
386
+ throw e;
387
+ // 그 외에는 Fallback CharSet 사용
388
+ state = this.getFallbackCharSet(dduOptions);
389
+ }
390
+ }
391
+ }
392
+ resolveInitialCharSet(dduChar, paddingChar, dduOptions, shouldThrow) {
393
+ // 내부 헬퍼: 길이와 옵션에 따라 최종 메타데이터 생성
394
+ const buildMeta = (set, padding, length, isPredefined) => {
395
+ const usePow2 = this.shouldUsePowerOfTwo(length, dduOptions?.usePowerOfTwo);
396
+ if (usePow2 && length > 0) {
397
+ const exponent = this.getLargestPowerOfTwoExponent(length);
398
+ const pow2Length = 1 << exponent;
399
+ return { charSet: set.slice(0, pow2Length), padding, requiredLength: pow2Length, bitLength: exponent, isPredefined };
400
+ }
401
+ return { charSet: set.slice(0, length), padding, requiredLength: length, bitLength: length > 0 ? this.getBitLength(length) : 0, isPredefined };
402
+ };
403
+ try {
404
+ const finalDduChar = dduChar ?? dduOptions?.dduChar;
405
+ const finalPadding = paddingChar ?? dduOptions?.paddingChar;
406
+ // Case A: 사용자 제공 CharSet
407
+ if (finalDduChar) {
408
+ if (!finalPadding)
409
+ throw new Error(`[Ddu64 Constructor] paddingChar is required when dduChar is provided.`);
410
+ const arr = typeof finalDduChar === "string" ? [...finalDduChar.trim()] : [...finalDduChar];
411
+ if (shouldThrow) {
412
+ const uniqueSize = new Set(arr).size;
413
+ if (uniqueSize !== arr.length) {
414
+ const duplicates = arr.filter((c, i) => arr.indexOf(c) !== i);
415
+ throw new Error(`[Ddu64 Constructor] Character set contains duplicate characters: [${[...new Set(duplicates)].join(", ")}]`);
416
+ }
417
+ }
418
+ const reqLen = dduOptions?.requiredLength ?? arr.length;
419
+ if (arr.length < reqLen)
420
+ throw new Error(`[Ddu64 Constructor] Insufficient characters.`);
421
+ return buildMeta(arr, finalPadding, reqLen, false);
422
+ }
423
+ // Case B: 심볼(Enum)로 지정된 CharSet
424
+ const symbol = dduOptions?.dduSetSymbol ?? dduDefaultConstructorOptions.dduSetSymbol ?? DduSetSymbol.DDU;
425
+ const cs = this.getCharSetOrThrow(symbol);
426
+ return buildMeta(cs.charSet, cs.paddingChar, cs.maxRequiredLength, true);
427
+ }
428
+ catch (error) {
429
+ if (shouldThrow)
430
+ throw error;
431
+ return this.getFallbackCharSet(dduOptions);
432
+ }
433
+ }
434
+ getFallbackCharSet(dduOptions) {
435
+ const symbol = dduOptions?.dduSetSymbol ?? dduDefaultConstructorOptions.dduSetSymbol ?? DduSetSymbol.ONECHARSET;
436
+ const cs = getCharSet(symbol) ?? getCharSet(DduSetSymbol.ONECHARSET);
437
+ if (!cs)
438
+ throw new Error(`Critical: No fallback CharSet available`);
439
+ return { charSet: cs.charSet, padding: cs.paddingChar, requiredLength: cs.maxRequiredLength, bitLength: cs.bitLength, isPredefined: true };
440
+ }
441
+ shouldUsePowerOfTwo(length, preference) {
442
+ if (preference !== undefined)
443
+ return preference ? length > 0 : false;
444
+ return length > 0 && (length & (length - 1)) === 0;
445
+ }
446
+ getCharSetOrThrow(symbol) {
447
+ const cs = getCharSet(symbol);
448
+ if (!cs)
449
+ throw new Error(`CharSet with symbol ${symbol} not found`);
450
+ return cs;
451
+ }
452
+ validateCombinationDuplicates(charSet, paddingChar, requiredLength) {
453
+ // 작은 크기의 단일 문자 집합에 대해서만 '조합 충돌' 검사를 수행 (안전장치)
454
+ if (charSet[0].length !== 1 || requiredLength > 256)
455
+ return;
456
+ const limit = Math.min(charSet.length, requiredLength);
457
+ const targetChars = charSet.slice(0, limit);
458
+ const combinations = new Set();
459
+ const add = (s, context) => {
460
+ if (combinations.has(s))
461
+ throw new Error(`Combination conflict: ${context}`);
462
+ combinations.add(s);
319
463
  };
464
+ targetChars.forEach(c => combinations.add(c));
465
+ combinations.add(paddingChar);
466
+ for (const c1 of targetChars) {
467
+ for (const c2 of targetChars)
468
+ add(c1 + c2, `"${c1}" + "${c2}"`);
469
+ add(c1 + paddingChar, `"${c1}" + padding`);
470
+ add(paddingChar + c1, `padding + "${c1}"`);
471
+ }
472
+ add(paddingChar + paddingChar, "double padding");
320
473
  }
321
474
  }