-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBaseEncoder.cs
More file actions
401 lines (323 loc) · 9.93 KB
/
Copy pathBaseEncoder.cs
File metadata and controls
401 lines (323 loc) · 9.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
using System;
using System.Buffers;
namespace Exyll;
/// <remarks>Based on http://www.csharp411.com/convert-binary-to-base64-string/</remarks>
public class BaseEncoder
{
const char PaddingChar = '=';
const int StackAllocThreshold = 256;
readonly byte[] _map;
public readonly char[] CharacterSet;
public readonly bool PaddingEnabled;
readonly int _base;
readonly int _bitsPerChar;
readonly int _charMask;
readonly int _charsPerBlock;
readonly bool _isPowerOfTwo;
public BaseEncoder(char[] characterSet, bool paddingEnabled)
{
PaddingEnabled = paddingEnabled;
CharacterSet = characterSet;
_base = characterSet.Length;
_isPowerOfTwo = (_base & (_base - 1)) == 0 && _base > 1;
if (_isPowerOfTwo)
{
int temp = _base;
while (temp > 1) { temp >>= 1; _bitsPerChar++; }
_charMask = (1 << _bitsPerChar) - 1;
_charsPerBlock = Lcm(8, _bitsPerChar) / _bitsPerChar;
}
_map = CreateMap(characterSet);
}
public virtual string ToBase(byte[]? data)
{
if (data is null || data.Length == 0) return string.Empty;
return ToBase((ReadOnlySpan<byte>)data);
}
public string ToBase(ReadOnlySpan<byte> data)
{
if (data.IsEmpty) return string.Empty;
return _isPowerOfTwo ? BitGroupEncode(data) : ArithmeticEncode(data);
}
public virtual byte[] FromBase(string? data)
{
if (string.IsNullOrEmpty(data)) return [];
return FromBase(data.AsSpan());
}
public byte[] FromBase(ReadOnlySpan<char> data)
{
if (data.IsEmpty) return [];
return _isPowerOfTwo ? BitGroupDecode(data) : ArithmeticDecode(data);
}
/// <summary>Encodes bytes into a caller-provided character buffer.</summary>
public bool TryEncode(ReadOnlySpan<byte> source, Span<char> destination, out int charsWritten)
{
charsWritten = 0;
if (source.IsEmpty) return true;
int needed = GetMaxEncodedLength(source.Length);
if (destination.Length < needed) return false;
if (_isPowerOfTwo)
BitGroupEncode(source, destination, out charsWritten);
else
ArithmeticEncode(source, destination, out charsWritten);
return true;
}
/// <summary>Decodes characters into a caller-provided byte buffer.</summary>
public bool TryDecode(ReadOnlySpan<char> source, Span<byte> destination, out int bytesWritten)
{
bytesWritten = 0;
if (source.IsEmpty) return true;
if (_isPowerOfTwo)
{
int needed = GetDecodedLength(source);
if (destination.Length < needed) return false;
BitGroupDecode(source, destination, out bytesWritten);
}
else
{
// Arithmetic: decode to temp, then copy
byte[] decoded = ArithmeticDecode(source);
if (destination.Length < decoded.Length) return false;
decoded.CopyTo(destination);
bytesWritten = decoded.Length;
}
return true;
}
/// <summary>Returns the maximum number of characters needed to encode the given number of bytes.</summary>
public int GetMaxEncodedLength(int byteCount)
{
if (byteCount == 0) return 0;
if (_isPowerOfTwo)
{
int charCount = (byteCount * 8 + _bitsPerChar - 1) / _bitsPerChar;
return PaddingEnabled
? (charCount + _charsPerBlock - 1) / _charsPerBlock * _charsPerBlock
: charCount;
}
// Arithmetic: upper bound
return (int)(byteCount * 8.0 / Math.Log2(_base)) + byteCount + 1;
}
/// <summary>Returns the exact number of bytes that the given encoded data will decode to.</summary>
public int GetDecodedLength(ReadOnlySpan<char> data)
{
if (data.IsEmpty) return 0;
if (_isPowerOfTwo)
{
int dataChars = data.Length;
while (dataChars > 0 && data[dataChars - 1] == PaddingChar)
dataChars--;
return dataChars * _bitsPerChar / 8;
}
// Arithmetic: can't compute without decoding
return ArithmeticDecode(data).Length;
}
// === Bit-group path (power-of-2 bases) ===
string BitGroupEncode(ReadOnlySpan<byte> data)
{
int allocLen = GetMaxEncodedLength(data.Length);
char[]? rented = null;
Span<char> buffer = allocLen <= StackAllocThreshold
? stackalloc char[allocLen]
: (rented = ArrayPool<char>.Shared.Rent(allocLen));
try
{
BitGroupEncode(data, buffer, out int written);
return new string(buffer[..written]);
}
finally
{
if (rented is not null) ArrayPool<char>.Shared.Return(rented);
}
}
void BitGroupEncode(ReadOnlySpan<byte> data, Span<char> output, out int written)
{
ReadOnlySpan<char> cs = CharacterSet;
int bitsPerChar = _bitsPerChar;
int charMask = _charMask;
int allocLen = GetMaxEncodedLength(data.Length);
int bitBuffer = 0, bitsInBuffer = 0, di = 0;
for (int i = 0; i < data.Length; i++)
{
bitBuffer = (bitBuffer << 8) | data[i];
bitsInBuffer += 8;
while (bitsInBuffer >= bitsPerChar)
{
bitsInBuffer -= bitsPerChar;
output[di++] = cs[(bitBuffer >> bitsInBuffer) & charMask];
}
}
if (bitsInBuffer > 0)
output[di++] = cs[(bitBuffer << (bitsPerChar - bitsInBuffer)) & charMask];
if (PaddingEnabled)
{
while (di < allocLen)
output[di++] = PaddingChar;
}
written = di;
}
byte[] BitGroupDecode(ReadOnlySpan<char> data)
{
int dataChars = data.Length;
while (dataChars > 0 && data[dataChars - 1] == PaddingChar)
dataChars--;
byte[] result = new byte[dataChars * _bitsPerChar / 8];
BitGroupDecode(data[..dataChars], result, out _);
return result;
}
void BitGroupDecode(ReadOnlySpan<char> data, Span<byte> output, out int written)
{
ReadOnlySpan<byte> map = _map;
int bitsPerChar = _bitsPerChar;
int bitBuffer = 0, bitsInBuffer = 0, di = 0;
for (int i = 0; i < data.Length; i++)
{
bitBuffer = (bitBuffer << bitsPerChar) | map[data[i]];
bitsInBuffer += bitsPerChar;
while (bitsInBuffer >= 8)
{
bitsInBuffer -= 8;
output[di++] = (byte)((bitBuffer >> bitsInBuffer) & 0xFF);
}
}
written = di;
}
// === Arithmetic path (non-power-of-2 bases) ===
string ArithmeticEncode(ReadOnlySpan<byte> data)
{
int maxLen = GetMaxEncodedLength(data.Length);
char[]? rented = null;
Span<char> buffer = maxLen <= StackAllocThreshold
? stackalloc char[maxLen]
: (rented = ArrayPool<char>.Shared.Rent(maxLen));
try
{
ArithmeticEncode(data, buffer, out int written);
return new string(buffer[..written]);
}
finally
{
if (rented is not null) ArrayPool<char>.Shared.Return(rented);
}
}
void ArithmeticEncode(ReadOnlySpan<byte> data, Span<char> output, out int written)
{
int length = data.Length;
int leadingZeros = 0;
while (leadingZeros < length && data[leadingZeros] == 0)
leadingZeros++;
if (leadingZeros == length)
{
output[..length].Fill(CharacterSet[0]);
written = length;
return;
}
// Work with a copy for in-place division
byte[]? rentedInput = null;
Span<byte> input = length <= StackAllocThreshold
? stackalloc byte[length]
: (rentedInput = ArrayPool<byte>.Shared.Rent(length));
try
{
data.CopyTo(input);
// Build result in reverse into output buffer
int resultEnd = output.Length;
int startIndex = leadingZeros;
while (startIndex < length)
{
int remainder = 0;
int newStart = length;
for (int i = startIndex; i < length; i++)
{
int acc = remainder * 256 + input[i];
input[i] = (byte)(acc / _base);
remainder = acc % _base;
if (input[i] != 0 && newStart == length)
newStart = i;
}
output[--resultEnd] = CharacterSet[remainder];
startIndex = newStart;
}
for (int i = 0; i < leadingZeros; i++)
output[--resultEnd] = CharacterSet[0];
int count = output.Length - resultEnd;
// Shift to start of output buffer
output[resultEnd..].CopyTo(output);
written = count;
}
finally
{
if (rentedInput is not null) ArrayPool<byte>.Shared.Return(rentedInput);
}
}
byte[] ArithmeticDecode(ReadOnlySpan<char> data)
{
int length = data.Length;
char zeroChar = CharacterSet[0];
int leadingZeros = 0;
while (leadingZeros < length && data[leadingZeros] == zeroChar)
leadingZeros++;
if (leadingZeros == length)
return new byte[length];
// Convert characters to digit values
ReadOnlySpan<byte> map = _map;
byte[]? rentedDigits = null;
Span<byte> digits = length <= StackAllocThreshold
? stackalloc byte[length]
: (rentedDigits = ArrayPool<byte>.Shared.Rent(length));
byte[]? rentedResult = null;
int resultSize = length * 2;
Span<byte> result = resultSize <= StackAllocThreshold
? stackalloc byte[resultSize]
: (rentedResult = ArrayPool<byte>.Shared.Rent(resultSize));
try
{
for (int i = 0; i < length; i++)
digits[i] = map[data[i]];
int resultIndex = result.Length;
int startIndex = leadingZeros;
while (startIndex < length)
{
int remainder = 0;
int newStart = length;
for (int i = startIndex; i < length; i++)
{
int acc = remainder * _base + digits[i];
digits[i] = (byte)(acc / 256);
remainder = acc % 256;
if (digits[i] != 0 && newStart == length)
newStart = i;
}
result[--resultIndex] = (byte)remainder;
startIndex = newStart;
}
for (int i = 0; i < leadingZeros; i++)
result[--resultIndex] = 0;
return result[resultIndex..].ToArray();
}
finally
{
if (rentedDigits is not null) ArrayPool<byte>.Shared.Return(rentedDigits);
if (rentedResult is not null) ArrayPool<byte>.Shared.Return(rentedResult);
}
}
// === Helpers ===
static byte[] CreateMap(char[] characterSet)
{
int maxChar = 0;
for (int i = 0; i < characterSet.Length; i++)
{
if (characterSet[i] > maxChar)
maxChar = characterSet[i];
}
byte[] map = new byte[maxChar + 1];
for (byte i = 0; i < characterSet.Length; i++)
map[characterSet[i]] = i;
return map;
}
static int Gcd(int a, int b)
{
while (b != 0) { int t = b; b = a % b; a = t; }
return a;
}
static int Lcm(int a, int b) => a / Gcd(a, b) * b;
}