-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUtf8StringPool.cs
More file actions
617 lines (517 loc) · 19 KB
/
Utf8StringPool.cs
File metadata and controls
617 lines (517 loc) · 19 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
// ReSharper disable InconsistentNaming - We used internal static fields to avoid unnecessary wrapping
namespace Combination.StringPools;
internal sealed class Utf8StringPool : IUtf8DeduplicatedStringPool
{
private const int
PoolIndexBits =
24; // Number of bits to use for pool index in handle (more bits = more pools, but less strings per pool)
private static readonly List<Utf8StringPool?> Pools = new();
#pragma warning disable IDE1006 // Naming Styles
internal static long totalAllocatedBytes;
internal static long totalUsedBytes;
internal static long totalAddedBytes;
#pragma warning restore IDE1006 // Naming Styles
internal int overfillCount;
private readonly List<nint> pages = new();
private readonly int index;
private long writePosition, usedBytes, addedBytes;
private ulong[]? deduplicationTable;
private readonly DisposeLock disposeLock = new();
private int deduplicationTableBits; // Number of bits to use for deduplication table (2^bits entries)
private readonly int pageSize;
private readonly object writeLock = new();
// ReSharper disable once MemberCanBePrivate.Global
public Utf8StringPool(int pageSize, int initialPageCount, bool deduplicateStrings, int deduplicationTableBits)
{
if (pageSize < 16)
{
// We need at least 16 bytes to store the length of the string and an actual string
throw new ArgumentOutOfRangeException(nameof(pageSize));
}
if (deduplicationTableBits < 2 || deduplicationTableBits > 24)
{
throw new ArgumentOutOfRangeException(nameof(deduplicationTableBits));
}
if (initialPageCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(initialPageCount));
}
this.deduplicationTableBits = deduplicationTableBits;
this.pageSize = pageSize;
if (deduplicateStrings)
{
deduplicationTable = new ulong[(1 << deduplicationTableBits)];
}
bool didAlloc;
lock (Pools)
{
if (Pools.Count >= (1 << PoolIndexBits) - 1)
{
throw new InvalidOperationException("Too many string pools allocated in process");
}
Pools.Add(this);
index = Pools.Count - 1;
didAlloc = EnsureCapacity(initialPageCount);
}
if (didAlloc)
{
AllocationChanged?.Invoke(this, EventArgs.Empty);
}
}
PooledUtf8String IUtf8StringPool.Add(ReadOnlySpan<char> value)
{
var utf8ByteCount = Encoding.UTF8.GetByteCount(value);
if (utf8ByteCount < 16384)
{
// Use the stack for small strings
Span<byte> utf8 = stackalloc byte[utf8ByteCount];
Encoding.UTF8.GetBytes(value, utf8);
return AddInternal(utf8);
}
var buffer = new byte[utf8ByteCount];
Encoding.UTF8.GetBytes(value, buffer);
return AddInternal(buffer);
}
PooledUtf8String IUtf8StringPool.Add(ReadOnlySpan<byte> value)
=> AddInternal(value);
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int GetAllocationSize(int length) => length + 1 + (BitOperations.Log2((uint)length) / 7);
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private PooledUtf8String AddInternal(ReadOnlySpan<byte> value)
{
var length = value.Length;
if (length == 0)
{
return PooledUtf8String.Empty;
}
var structLength = GetAllocationSize(length);
if (structLength > pageSize)
{
throw new ArgumentOutOfRangeException(nameof(value), "String is too long to be pooled");
}
var stringHash = 0;
var didAlloc = false;
var oldSize = Interlocked.Read(ref usedBytes);
Interlocked.Add(ref totalAddedBytes, structLength);
Interlocked.Add(ref addedBytes, structLength);
if (deduplicationTable is not null)
{
stringHash = unchecked((int)StringHash.Compute(value));
if (TryDeduplicate(stringHash, value, out var result))
{
return new PooledUtf8String(result);
}
}
lock (writeLock)
{
if (disposeLock.IsDisposed)
{
throw new ObjectDisposedException("String pool is already disposed");
}
if (oldSize != Interlocked.Read(ref usedBytes) && TryDeduplicate(stringHash, value, out var result))
{
return new PooledUtf8String(result);
}
var currentPageIndex = checked((int)(writePosition / pageSize));
var pageWritePosition = writePosition % pageSize;
nint writePtr;
int pageStartOffset;
if (pageSize - pageWritePosition >= structLength)
{
if (pageWritePosition == 0)
{
didAlloc = EnsureCapacity(currentPageIndex + 1);
}
writePtr = pages[currentPageIndex];
pageStartOffset = (int)pageWritePosition;
writePosition += structLength;
}
else
{
++currentPageIndex;
writePosition = (currentPageIndex * (long)pageSize) + structLength;
didAlloc = EnsureCapacity(currentPageIndex + 1);
writePtr = pages[currentPageIndex];
pageStartOffset = 0;
}
unsafe
{
var ptr = (byte*)(writePtr + pageStartOffset);
var write = length;
while (true)
{
if (write > 0x7f)
{
*ptr++ = unchecked((byte)(0x80 | (write & 0x7f)));
}
else
{
*ptr++ = unchecked((byte)write);
break;
}
write >>= 7;
}
var stringWritePtr = new Span<byte>(ptr, length);
value.CopyTo(stringWritePtr);
}
var handle = ((ulong)index << (64 - PoolIndexBits)) | (ulong)(writePosition - structLength);
if (deduplicationTable is not null)
{
AddToDeduplicationTable(deduplicationTable, deduplicationTableBits, stringHash, handle);
}
Interlocked.Add(ref totalUsedBytes, structLength);
Interlocked.Add(ref usedBytes, structLength);
if (didAlloc)
{
AllocationChanged?.Invoke(this, EventArgs.Empty);
}
StringAdded?.Invoke(this, EventArgs.Empty);
return new PooledUtf8String(handle);
}
}
long IStringPool.AddedBytes => addedBytes;
long IStringPool.UsedBytes => usedBytes;
long IStringPool.AllocatedBytes => pages.Count * pageSize;
PooledUtf8String? IUtf8DeduplicatedStringPool.TryGet(ReadOnlySpan<char> value)
{
var utf8ByteCount = Encoding.UTF8.GetByteCount(value);
if (utf8ByteCount < 16384)
{
// Use the stack for small strings
Span<byte> utf8 = stackalloc byte[utf8ByteCount];
Encoding.UTF8.GetBytes(value, utf8);
return TryGetInternal(utf8);
}
var buffer = new byte[utf8ByteCount];
Encoding.UTF8.GetBytes(value, buffer);
return TryGetInternal(buffer);
}
PooledUtf8String? IUtf8DeduplicatedStringPool.TryGet(ReadOnlySpan<byte> value)
=> TryGetInternal(value);
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private PooledUtf8String? TryGetInternal(ReadOnlySpan<byte> value)
{
if (value.Length == 0)
{
return PooledUtf8String.Empty;
}
if (deduplicationTable is null)
{
throw new InvalidOperationException("Deduplication is not enabled for this pool");
}
if (!TryDeduplicate(unchecked((int)StringHash.Compute(value)), value, out var result))
{
return null;
}
return new PooledUtf8String(result);
}
private bool TryDeduplicate(int stringHash, ReadOnlySpan<byte> value, out ulong offset)
{
using (disposeLock.PreventDispose())
{
if (deduplicationTable == null)
{
offset = ulong.MaxValue;
return false;
}
var tableSize = 1 << deduplicationTableBits;
var tableIndex = stringHash & (tableSize - 1);
for (var i = 0; i < tableSize; i++)
{
var tableEntry = deduplicationTable[(tableIndex + i) % tableSize];
if (tableEntry == 0)
{
offset = ulong.MaxValue;
return false;
}
var handle = tableEntry - 1;
var poolOffset = handle & ((1UL << (64 - PoolIndexBits)) - 1);
var poolBytes = GetStringBytes(poolOffset);
if (poolBytes.Length == value.Length && value.SequenceEqual(poolBytes))
{
offset = handle;
return true;
}
}
offset = ulong.MaxValue;
return false;
}
}
private void AddToDeduplicationTable(ulong[]? currentTable, int currentTableBits, int stringHash, ulong handle)
{
if (currentTable == null)
{
return;
}
var tableSize = 1 << currentTableBits;
var tableIndex = stringHash & (tableSize - 1);
for (var i = 0; i < tableSize; i++)
{
var tableEntry = currentTable[(tableIndex + i) % tableSize];
if (tableEntry == 0)
{
if (i > 0)
{
++overfillCount;
}
currentTable[(tableIndex + i) % tableSize] = handle + 1;
if (overfillCount > tableSize / 2)
{
ResizeDeduplicationTable(currentTableBits + 1);
}
return;
}
}
ResizeDeduplicationTable(currentTableBits + 1);
}
private void ResizeDeduplicationTable(int newBits)
{
if (deduplicationTable is null)
{
return;
}
var newDeduplicationTable = new ulong[1 << newBits];
overfillCount = 0;
var tableSize = 1 << deduplicationTableBits;
for (var i = 0; i < tableSize; ++i)
{
var tableEntry = deduplicationTable[i];
if (tableEntry != 0)
{
var handle = tableEntry - 1;
var poolOffset = handle & ((1UL << (64 - PoolIndexBits)) - 1);
var poolBytes = GetStringBytes(poolOffset);
AddToDeduplicationTable(newDeduplicationTable, newBits, (int)StringHash.Compute(poolBytes), handle);
}
}
deduplicationTable = newDeduplicationTable;
deduplicationTableBits = newBits;
}
public static string Get(ulong handle)
{
if (handle == ulong.MaxValue)
{
return string.Empty;
}
return Encoding.UTF8.GetString(GetBytes(handle));
}
public static ReadOnlySpan<byte> GetBytes(ulong handle)
{
if (handle == ulong.MaxValue)
{
return Array.Empty<byte>();
}
var poolIndex = handle >> (64 - PoolIndexBits);
if (poolIndex >= (ulong)Pools.Count)
{
throw new ArgumentException("Bad string pool offset", nameof(handle));
}
var pool = Pools[(int)poolIndex] ?? throw new ObjectDisposedException("String pool is disposed");
return pool.GetFromPool(handle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private ReadOnlySpan<byte> GetFromPool(ulong handle)
{
using (disposeLock.PreventDispose())
{
var offset = handle & ((1UL << (64 - PoolIndexBits)) - 1);
#if DEBUG
var poolIndex = handle >> (64 - PoolIndexBits);
var refPool = Pools[(int)poolIndex];
if (refPool != this)
{
throw new InvalidOperationException($"Internal error: Deduplicated string pool mismatch ({index} != {poolIndex})");
}
#endif
return GetStringBytes(offset);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private ReadOnlySpan<byte> GetStringBytes(ulong offset)
{
var page = checked((int)(offset / (ulong)pageSize));
var pageOffset = (int)(offset % (ulong)pageSize);
if (page < 0 || page >= pages.Count)
{
throw new ArgumentOutOfRangeException(
nameof(offset),
$"Invalid handle value, page {page} is out of range 0..{pages.Count}, strings {addedBytes} {usedBytes} --- {offset}");
}
unsafe
{
var ptr = (byte*)(pages[page] + pageOffset);
var length = 0;
var shl = 0;
while (true)
{
var t = *ptr++;
length += (t & 0x7f) << shl;
shl += 7;
if ((t & 0x80) == 0)
{
break;
}
}
return new ReadOnlySpan<byte>(ptr, length);
}
}
public static int GetLength(ulong handle)
{
if (handle == ulong.MaxValue)
{
return 0;
}
var poolIndex = (handle >> (64 - PoolIndexBits)) & ((1 << PoolIndexBits) - 1);
if (poolIndex >= (ulong)Pools.Count)
{
throw new ArgumentException("Bad string pool offset", nameof(handle));
}
var pool = Pools[(int)poolIndex] ?? throw new ObjectDisposedException("String pool is disposed");
return pool.GetStringLength(handle & ((1L << (64 - PoolIndexBits)) - 1));
}
public static IUtf8StringPool? GetStringPool(ulong handle)
{
if (handle == ulong.MaxValue)
{
return null;
}
var poolIndex = handle >> (64 - PoolIndexBits);
return poolIndex >= (ulong)Pools.Count ? null : Pools[(int)poolIndex];
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private int GetStringLength(ulong offset)
{
using (disposeLock.PreventDispose())
{
var page = checked((int)(offset / (ulong)pageSize));
var pageOffset = (int)(offset % (ulong)pageSize);
if (page < 0 || page >= pages.Count)
{
throw new ArgumentOutOfRangeException(nameof(offset), $"Invalid handle value, page {page} is out of range 0..{pages.Count}");
}
unsafe
{
var ptr = (byte*)(pages[page] + pageOffset);
var length = 0;
var shl = 0;
while (true)
{
var t = *ptr++;
length += (t & 0x7f) << shl;
shl += 7;
if ((t & 0x80) == 0)
{
break;
}
}
return length;
}
}
}
private bool EnsureCapacity(int numPages)
{
if (numPages <= pages.Count)
{
return false;
}
for (var i = pages.Count; i < numPages; i++)
{
pages.Add(Marshal.AllocHGlobal(pageSize));
Interlocked.Add(ref totalAllocatedBytes, pageSize);
}
return true;
}
public static event EventHandler? AllocationChanged;
public static event EventHandler? StringAdded;
~Utf8StringPool()
{
Deallocate();
}
public void Dispose()
{
GC.SuppressFinalize(this);
Deallocate();
}
private void Deallocate()
{
disposeLock.BeginDispose();
lock (Pools)
{
Pools[index] = null;
}
lock (writeLock)
{
foreach (var page in pages)
{
Interlocked.Add(ref totalAllocatedBytes, -pageSize);
Marshal.FreeHGlobal(page);
}
Interlocked.Add(ref totalUsedBytes, -usedBytes);
Interlocked.Add(ref totalAddedBytes, -addedBytes);
usedBytes = addedBytes = 0;
pages.Clear();
}
// Don't send this here since we are being deallocated
AllocationChanged?.Invoke(null, EventArgs.Empty);
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
internal static bool StringsEqual(ulong a, ulong b)
{
return StringsCompare(a, b) == 0;
}
public override string ToString() =>
$"Utf8StringPool(bits={deduplicationTableBits}, dedup={deduplicationTable is not null}, pages={pages.Count}, used={usedBytes}, added={addedBytes})";
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
public static int StringsCompare(ulong a, ulong b)
{
if (a == ulong.MaxValue)
{
return b == ulong.MaxValue ? 0 : -1;
}
if (b == ulong.MaxValue)
{
return 1;
}
if (a == b)
{
return 0;
}
var aPoolIndex = a >> (64 - PoolIndexBits);
var bPoolIndex = b >> (64 - PoolIndexBits);
if (aPoolIndex >= (ulong)Pools.Count)
{
throw new ArgumentException("Bad string pool offset", nameof(a));
}
if (bPoolIndex >= (ulong)Pools.Count)
{
throw new ArgumentException("Bad string pool offset", nameof(b));
}
var aOffset = a & ((1L << (64 - PoolIndexBits)) - 1);
var bOffset = b & ((1L << (64 - PoolIndexBits)) - 1);
var aPool = Pools[(int)aPoolIndex] ?? throw new ObjectDisposedException("String pool is disposed");
if (aPoolIndex != bPoolIndex)
{
var bPool = Pools[(int)bPoolIndex] ?? throw new ObjectDisposedException("String pool is disposed");
using (aPool.disposeLock.PreventDispose())
{
using (bPool.disposeLock.PreventDispose())
{
return aPool.GetStringBytes(aOffset).SequenceCompareTo(bPool.GetStringBytes(bOffset));
}
}
}
if (aPool.deduplicationTable is not null && aOffset == bOffset)
{
// If the strings are in the same deduplicated pool, we can just compare the offsets
return 0;
}
using (aPool.disposeLock.PreventDispose())
{
return aPool.GetStringBytes(aOffset).SequenceCompareTo(aPool.GetStringBytes(bOffset));
}
}
}