-
-
Notifications
You must be signed in to change notification settings - Fork 710
/
Copy pathAutomataDictionary.cs
679 lines (615 loc) · 24.8 KB
/
AutomataDictionary.cs
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Reflection.Emit;
using System.Reflection;
namespace MessagePack.Internal
{
// Key = long, Value = int for UTF8String Dictionary
public class AutomataDictionary : IEnumerable<KeyValuePair<string, int>>
{
readonly AutomataNode root;
public AutomataDictionary()
{
root = new AutomataNode(-1);
}
#if NETSTANDARD1_4
public unsafe void Add(string str, int value)
{
var bytes = Encoding.UTF8.GetBytes(str);
fixed (byte* buffer = bytes)
{
var node = root;
var p = buffer;
var rest = bytes.Length;
while (rest != 0)
{
var key = AutomataKeyGen.GetKey(ref p, ref rest);
if (rest == 0)
{
node = node.Add(key, value, str);
}
else
{
node = node.Add(key);
}
}
}
}
public unsafe bool TryGetValue(byte[] bytes, int offset, int count, out int value)
{
fixed (byte* p = bytes)
{
var p1 = p;
var node = root;
var rest = count;
while (rest != 0 && node != null)
{
node = node.SearchNext(ref p1, ref rest);
}
if (node == null)
{
value = -1;
return false;
}
else
{
value = node.Value;
return true;
}
}
}
#else
// for Unity, use safe only.
public void Add(string str, int value)
{
var bytes = Encoding.UTF8.GetBytes(str);
var offset = 0;
var node = root;
var rest = bytes.Length;
while (rest != 0)
{
var key = AutomataKeyGen.GetKeySafe(bytes, ref offset, ref rest);
if (rest == 0)
{
node = node.Add(key, value, str);
}
else
{
node = node.Add(key);
}
}
}
#endif
public bool TryGetValueSafe(ArraySegment<byte> key, out int value)
{
var node = root;
var bytes = key.Array;
var offset = key.Offset;
var rest = key.Count;
while (rest != 0 && node != null)
{
node = node.SearchNextSafe(bytes, ref offset, ref rest);
}
if (node == null)
{
value = -1;
return false;
}
else
{
value = node.Value;
return true;
}
}
// for debugging
public override string ToString()
{
var sb = new StringBuilder();
ToStringCore(root.YieldChildren(), sb, 0);
return sb.ToString();
}
static void ToStringCore(IEnumerable<AutomataNode> nexts, StringBuilder sb, int depth)
{
foreach (var item in nexts)
{
if (depth != 0)
{
sb.Append(' ', depth * 2);
}
sb.Append("[" + item.Key + "]");
if (item.Value != -1)
{
sb.Append("(" + item.originalKey + ")");
sb.Append(" = ");
sb.Append(item.Value);
}
sb.AppendLine();
ToStringCore(item.YieldChildren(), sb, depth + 1);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<string, int>> GetEnumerator()
{
return YieldCore(this.root.YieldChildren()).GetEnumerator();
}
static IEnumerable<KeyValuePair<string, int>> YieldCore(IEnumerable<AutomataNode> nexts)
{
foreach (var item in nexts)
{
if (item.Value != -1) yield return new KeyValuePair<string, int>(item.originalKey, item.Value);
YieldCore(item.YieldChildren());
}
}
// IL Emit
public void EmitMatch(ILGenerator il, LocalBuilder p, LocalBuilder rest, LocalBuilder key, Action<KeyValuePair<string, int>> onFound, Action onNotFound)
{
root.EmitSearchNext(il, p, rest, key, onFound, onNotFound);
}
class AutomataNode : IComparable<AutomataNode>
{
static readonly AutomataNode[] emptyNodes = new AutomataNode[0];
static readonly long[] emptyKeys = new long[0];
public long Key;
public int Value;
public string originalKey;
AutomataNode[] nexts;
long[] nextKeys;
int count;
public bool HasChildren { get { return count != 0; } }
public AutomataNode(long key)
{
this.Key = key;
this.Value = -1;
this.nexts = emptyNodes;
this.nextKeys = emptyKeys;
this.count = 0;
this.originalKey = null;
}
public AutomataNode Add(long key)
{
var index = Array.BinarySearch(nextKeys, 0, count, key);
if (index < 0)
{
if (nexts.Length == count)
{
Array.Resize<AutomataNode>(ref nexts, (count == 0) ? 4 : (count * 2));
Array.Resize<long>(ref nextKeys, (count == 0) ? 4 : (count * 2));
}
count++;
var nextNode = new AutomataNode(key);
nexts[count - 1] = nextNode;
nextKeys[count - 1] = key;
Array.Sort(nexts, 0, count);
Array.Sort(nextKeys, 0, count);
return nextNode;
}
else
{
return nexts[index];
}
}
public AutomataNode Add(long key, int value, string originalKey)
{
var v = Add(key);
v.Value = value;
v.originalKey = originalKey;
return v;
}
public unsafe AutomataNode SearchNext(ref byte* p, ref int rest)
{
var key = AutomataKeyGen.GetKey(ref p, ref rest);
if (count < 4)
{
// linear search
for (int i = 0; i < count; i++)
{
if (nextKeys[i] == key)
{
return nexts[i];
}
}
}
else
{
// binary search
var index = BinarySearch(nextKeys, 0, count, key);
if (index >= 0)
{
return nexts[index];
}
}
return null;
}
public unsafe AutomataNode SearchNextSafe(byte[] p, ref int offset, ref int rest)
{
var key = AutomataKeyGen.GetKeySafe(p, ref offset, ref rest);
if (count < 4)
{
// linear search
for (int i = 0; i < count; i++)
{
if (nextKeys[i] == key)
{
return nexts[i];
}
}
}
else
{
// binary search
var index = BinarySearch(nextKeys, 0, count, key);
if (index >= 0)
{
return nexts[index];
}
}
return null;
}
internal static int BinarySearch(long[] array, int index, int length, long value)
{
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
var arrayValue = array[i];
int order;
if (arrayValue < value) order = -1;
else if (arrayValue > value) order = 1;
else order = 0;
if (order == 0) return i;
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
public int CompareTo(AutomataNode other)
{
return this.Key.CompareTo(other.Key);
}
public IEnumerable<AutomataNode> YieldChildren()
{
for (int i = 0; i < count; i++)
{
yield return nexts[i];
}
}
// SearchNext(ref byte* p, ref int rest, ref long key)
public void EmitSearchNext(ILGenerator il, LocalBuilder p, LocalBuilder rest, LocalBuilder key, Action<KeyValuePair<string, int>> onFound, Action onNotFound)
{
// key = AutomataKeyGen.GetKey(ref p, ref rest);
il.EmitLdloca(p);
il.EmitLdloca(rest);
il.EmitCall(AutomataKeyGen.GetKeyMethod);
il.EmitStloc(key);
// match children.
EmitSearchNextCore(il, p, rest, key, onFound, onNotFound, nexts, count);
}
static void EmitSearchNextCore(ILGenerator il, LocalBuilder p, LocalBuilder rest, LocalBuilder key, Action<KeyValuePair<string, int>> onFound, Action onNotFound, AutomataNode[] nexts, int count)
{
if (count < 4)
{
// linear-search
var valueExists = nexts.Take(count).Where(x => x.Value != -1).ToArray();
var childrenExists = nexts.Take(count).Where(x => x.HasChildren).ToArray();
var gotoSearchNext = il.DefineLabel();
var gotoNotFound = il.DefineLabel();
{
il.EmitLdloc(rest);
if (childrenExists.Length != 0 && valueExists.Length == 0)
{
il.Emit(OpCodes.Brfalse, gotoNotFound); // if(rest == 0)
}
else
{
il.Emit(OpCodes.Brtrue, gotoSearchNext); // if(rest != 0)
}
}
{
var ifValueNexts = Enumerable.Range(0, Math.Max(valueExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray();
for (int i = 0; i < valueExists.Length; i++)
{
var notFoundLabel = il.DefineLabel();
if (i != 0)
{
il.MarkLabel(ifValueNexts[i - 1]);
}
il.EmitLdloc(key);
il.Emit(OpCodes.Ldc_I8, valueExists[i].Key);
il.Emit(OpCodes.Bne_Un, notFoundLabel);
// found
onFound(new KeyValuePair<string, int>(nexts[i].originalKey, nexts[i].Value));
// notfound
il.MarkLabel(notFoundLabel);
if (i != valueExists.Length - 1)
{
il.Emit(OpCodes.Br, ifValueNexts[i]);
}
else
{
onNotFound();
}
}
}
il.MarkLabel(gotoSearchNext);
var ifRecNext = Enumerable.Range(0, Math.Max(childrenExists.Length - 1, 0)).Select(_ => il.DefineLabel()).ToArray();
for (int i = 0; i < childrenExists.Length; i++)
{
var notFoundLabel = il.DefineLabel();
if (i != 0)
{
il.MarkLabel(ifRecNext[i - 1]);
}
il.EmitLdloc(key);
il.Emit(OpCodes.Ldc_I8, childrenExists[i].Key);
il.Emit(OpCodes.Bne_Un, notFoundLabel);
// found
childrenExists[i].EmitSearchNext(il, p, rest, key, onFound, onNotFound);
// notfound
il.MarkLabel(notFoundLabel);
if (i != childrenExists.Length - 1)
{
il.Emit(OpCodes.Br, ifRecNext[i]);
}
else
{
onNotFound();
}
}
il.MarkLabel(gotoNotFound);
onNotFound();
}
else
{
// binary-search
var midline = count / 2;
var mid = nexts[midline].Key;
var l = nexts.Take(count).Take(midline).ToArray();
var r = nexts.Take(count).Skip(midline).ToArray();
var gotoRight = il.DefineLabel();
// if(key < mid)
il.EmitLdloc(key);
il.Emit(OpCodes.Ldc_I8, mid);
il.Emit(OpCodes.Bge, gotoRight);
EmitSearchNextCore(il, p, rest, key, onFound, onNotFound, l, l.Length);
// else
il.MarkLabel(gotoRight);
EmitSearchNextCore(il, p, rest, key, onFound, onNotFound, r, r.Length);
}
}
}
}
public static class AutomataKeyGen
{
public static readonly MethodInfo GetKeyMethod = typeof(AutomataKeyGen).GetRuntimeMethod("GetKey", new[] { typeof(byte*).MakeByRefType(), typeof(int).MakeByRefType() });
// public static readonly MethodInfo GetKeySafeMethod = typeof(AutomataKeyGen).GetRuntimeMethod("GetKeySafe", new[] { typeof(byte[]), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() });
public static unsafe long GetKey(ref byte* p, ref int rest)
{
int readSize;
long key;
unchecked
{
if (rest >= 8)
{
key = *(long*)p;
readSize = 8;
}
else
{
switch (rest)
{
case 1:
{
key = *(byte*)p;
readSize = 1;
break;
}
case 2:
{
key = *(short*)p;
readSize = 2;
break;
}
case 3:
{
var a = *p;
var b = *(short*)(p + 1);
key = ((long)a | (long)b << 8);
readSize = 3;
break;
}
case 4:
{
key = *(int*)p;
readSize = 4;
break;
}
case 5:
{
var a = *p;
var b = *(int*)(p + 1);
key = ((long)a | (long)b << 8);
readSize = 5;
break;
}
case 6:
{
var a = *(short*)p;
var b = *(int*)(p + 2);
key = ((long)a | (long)b << 16);
readSize = 6;
break;
}
case 7:
{
var a = *(byte*)p;
var b = *(short*)(p + 1);
var c = *(int*)(p + 3);
key = ((long)a | (long)b << 8 | (long)c << 24);
readSize = 7;
break;
}
default:
throw new InvalidOperationException("Not Supported Length");
}
}
p += readSize;
rest -= readSize;
return key;
}
}
public static long GetKeySafe(byte[] bytes, ref int offset, ref int rest)
{
int readSize;
long key;
if (BitConverter.IsLittleEndian)
{
unchecked
{
if (rest >= 8)
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 24
| (long)bytes[offset + 4] << 32 | (long)bytes[offset + 5] << 40 | (long)bytes[offset + 6] << 48 | (long)bytes[offset + 7] << 56;
readSize = 8;
}
else
{
switch (rest)
{
case 1:
{
key = bytes[offset];
readSize = 1;
break;
}
case 2:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8;
readSize = 2;
break;
}
case 3:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16;
readSize = 3;
break;
}
case 4:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 24;
readSize = 4;
break;
}
case 5:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 24
| (long)bytes[offset + 4] << 32;
readSize = 5;
break;
}
case 6:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 24
| (long)bytes[offset + 4] << 32 | (long)bytes[offset + 5] << 40;
readSize = 6;
break;
}
case 7:
{
key = (long)bytes[offset] << 0 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 24
| (long)bytes[offset + 4] << 32 | (long)bytes[offset + 5] << 40 | (long)bytes[offset + 6] << 48;
readSize = 7;
break;
}
default:
throw new InvalidOperationException("Not Supported Length");
}
}
offset += readSize;
rest -= readSize;
return key;
}
}
else
{
unchecked
{
if (rest >= 8)
{
key = (long)bytes[offset] << 56 | (long)bytes[offset + 1] << 48 | (long)bytes[offset + 2] << 40 | (long)bytes[offset + 3] << 32
| (long)bytes[offset + 4] << 24 | (long)bytes[offset + 5] << 16 | (long)bytes[offset + 6] << 8 | (long)bytes[offset + 7];
readSize = 8;
}
else
{
switch (rest)
{
case 1:
{
key = bytes[offset];
readSize = 1;
break;
}
case 2:
{
key = (long)bytes[offset] << 8 | (long)bytes[offset + 1] << 0;
readSize = 2;
break;
}
case 3:
{
key = (long)bytes[offset] << 16 | (long)bytes[offset + 1] << 8 | (long)bytes[offset + 2] << 0;
readSize = 3;
break;
}
case 4:
{
key = (long)bytes[offset] << 24 | (long)bytes[offset + 1] << 16 | (long)bytes[offset + 2] << 8 | (long)bytes[offset + 3] << 0;
readSize = 4;
break;
}
case 5:
{
key = (long)bytes[offset] << 32 | (long)bytes[offset + 1] << 24 | (long)bytes[offset + 2] << 16 | (long)bytes[offset + 3] << 8
| (long)bytes[offset + 4] << 0;
readSize = 5;
break;
}
case 6:
{
key = (long)bytes[offset] << 40 | (long)bytes[offset + 1] << 32 | (long)bytes[offset + 2] << 24 | (long)bytes[offset + 3] << 16
| (long)bytes[offset + 4] << 8 | (long)bytes[offset + 5] << 0;
readSize = 6;
break;
}
case 7:
{
key = (long)bytes[offset] << 48 | (long)bytes[offset + 1] << 40 | (long)bytes[offset + 2] << 32 | (long)bytes[offset + 3] << 24
| (long)bytes[offset + 4] << 16 | (long)bytes[offset + 5] << 8 | (long)bytes[offset + 6] << 0;
readSize = 7;
break;
}
default:
throw new InvalidOperationException("Not Supported Length");
}
}
offset += readSize;
rest -= readSize;
return key;
}
}
}
}
}