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