-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ArrayTernaryTrie.java
716 lines (626 loc) · 18.8 KB
/
ArrayTernaryTrie.java
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util;
import java.nio.ByteBuffer;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>A Ternary Trie String lookup data structure.</p>
* <p>
* This Trie is of a fixed size and cannot grow (which can be a good thing with regards to DOS when used as a cache).
* </p>
* <p>
* The Trie is stored in 3 arrays:
* </p>
* <dl>
* <dt>char[] _tree</dt><dd>This is semantically 2 dimensional array flattened into a 1 dimensional char array. The second dimension
* is that every 4 sequential elements represents a row of: character; hi index; eq index; low index, used to build a
* ternary trie of key strings.</dd>
* <dt>String[] _key</dt><dd>An array of key values where each element matches a row in the _tree array. A non zero key element
* indicates that the _tree row is a complete key rather than an intermediate character of a longer key.</dd>
* <dt>V[] _value</dt><dd>An array of values corresponding to the _key array</dd>
* </dl>
* <p>The lookup of a value will iterate through the _tree array matching characters. If the equal tree branch is followed,
* then the _key array is looked up to see if this is a complete match. If a match is found then the _value array is looked up
* to return the matching value.
* </p>
* <p>
* This Trie may be instantiated either as case sensitive or insensitive.
* </p>
* <p>This Trie is not Threadsafe and contains no mutual exclusion
* or deliberate memory barriers. It is intended for an ArrayTrie to be
* built by a single thread and then used concurrently by multiple threads
* and not mutated during that access. If concurrent mutations of the
* Trie is required external locks need to be applied.
* </p>
*
* @param <V> the Entry type
*/
public class ArrayTernaryTrie<V> extends AbstractTrie<V>
{
private static int LO = 1;
private static int EQ = 2;
private static int HI = 3;
/**
* The Size of a Trie row is the char, and the low, equal and high
* child pointers
*/
private static final int ROW_SIZE = 4;
/**
* The Trie rows in a single array which allows a lookup of row,character
* to the next row in the Trie. This is actually a 2 dimensional
* array that has been flattened to achieve locality of reference.
*/
private final char[] _tree;
/**
* The key (if any) for a Trie row.
* A row may be a leaf, a node or both in the Trie tree.
*/
private final String[] _key;
/**
* The value (if any) for a Trie row.
* A row may be a leaf, a node or both in the Trie tree.
*/
private final V[] _value;
/**
* The number of rows allocated
*/
private char _rows;
/**
* Create a case insensitive Trie of default capacity.
*/
public ArrayTernaryTrie()
{
this(128);
}
/**
* Create a Trie of default capacity
*
* @param insensitive true if the Trie is insensitive to the case of the key.
*/
public ArrayTernaryTrie(boolean insensitive)
{
this(insensitive, 128);
}
/**
* Create a case insensitive Trie
*
* @param capacity The capacity of the Trie, which is in the worst case
* is the total number of characters of all keys stored in the Trie.
* The capacity needed is dependent of the shared prefixes of the keys.
* For example, a capacity of 6 nodes is required to store keys "foo"
* and "bar", but a capacity of only 4 is required to
* store "bar" and "bat".
*/
public ArrayTernaryTrie(int capacity)
{
this(true, capacity);
}
/**
* Create a Trie
*
* @param insensitive true if the Trie is insensitive to the case of the key.
* @param capacity The capacity of the Trie, which is in the worst case
* is the total number of characters of all keys stored in the Trie.
* The capacity needed is dependent of the shared prefixes of the keys.
* For example, a capacity of 6 nodes is required to store keys "foo"
* and "bar", but a capacity of only 4 is required to
* store "bar" and "bat".
*/
public ArrayTernaryTrie(boolean insensitive, int capacity)
{
super(insensitive);
_value = (V[])new Object[capacity];
_tree = new char[capacity * ROW_SIZE];
_key = new String[capacity];
}
/**
* Copy Trie and change capacity by a factor
*
* @param trie the trie to copy from
* @param factor the factor to grow the capacity by
*/
public ArrayTernaryTrie(ArrayTernaryTrie<V> trie, double factor)
{
super(trie.isCaseInsensitive());
int capacity = (int)(trie._value.length * factor);
_rows = trie._rows;
_value = Arrays.copyOf(trie._value, capacity);
_tree = Arrays.copyOf(trie._tree, capacity * ROW_SIZE);
_key = Arrays.copyOf(trie._key, capacity);
}
@Override
public void clear()
{
_rows = 0;
Arrays.fill(_value, null);
Arrays.fill(_tree, (char)0);
Arrays.fill(_key, null);
}
@Override
public boolean put(String s, V v)
{
int t = 0;
int limit = s.length();
int last = 0;
for (int k = 0; k < limit; k++)
{
char c = s.charAt(k);
if (isCaseInsensitive() && c < 128)
c = StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
// Do we need to create the new row?
if (t == _rows)
{
_rows++;
if (_rows >= _key.length)
{
_rows--;
return false;
}
_tree[row] = c;
}
char n = _tree[row];
int diff = n - c;
if (diff == 0)
t = _tree[last = (row + EQ)];
else if (diff < 0)
t = _tree[last = (row + LO)];
else
t = _tree[last = (row + HI)];
// do we need a new row?
if (t == 0)
{
t = _rows;
_tree[last] = (char)t;
}
if (diff == 0)
break;
}
}
// Do we need to create the new row?
if (t == _rows)
{
_rows++;
if (_rows >= _key.length)
{
_rows--;
return false;
}
}
// Put the key and value
_key[t] = v == null ? null : s;
_value[t] = v;
return true;
}
@Override
public V get(String s, int offset, int len)
{
int t = 0;
for (int i = 0; i < len; )
{
char c = s.charAt(offset + i++);
if (isCaseInsensitive() && c < 128)
c = StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0)
{
t = _tree[row + EQ];
if (t == 0)
return null;
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
return null;
}
}
return _value[t];
}
@Override
public V get(ByteBuffer b, int offset, int len)
{
int t = 0;
offset += b.position();
for (int i = 0; i < len; )
{
byte c = (byte)(b.get(offset + i++) & 0x7f);
if (isCaseInsensitive())
c = (byte)StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0)
{
t = _tree[row + EQ];
if (t == 0)
return null;
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
return null;
}
}
return _value[t];
}
@Override
public V getBest(String s)
{
return getBest(0, s, 0, s.length());
}
@Override
public V getBest(String s, int offset, int length)
{
return getBest(0, s, offset, length);
}
private V getBest(int t, String s, int offset, int len)
{
int node = t;
int end = offset + len;
loop:
while (offset < end)
{
char c = s.charAt(offset++);
len--;
if (isCaseInsensitive() && c < 128)
c = StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0)
{
t = _tree[row + EQ];
if (t == 0)
break loop;
// if this node is a match, recurse to remember
if (_key[t] != null)
{
node = t;
V better = getBest(t, s, offset, len);
if (better != null)
return better;
}
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
break loop;
}
}
return _value[node];
}
@Override
public V getBest(ByteBuffer b, int offset, int len)
{
if (b.hasArray())
return getBest(0, b.array(), b.arrayOffset() + b.position() + offset, len);
return getBest(0, b, offset, len);
}
@Override
public V getBest(byte[] b, int offset, int len)
{
return getBest(0, b, offset, len);
}
private V getBest(int t, byte[] b, int offset, int len)
{
int node = t;
int end = offset + len;
loop:
while (offset < end)
{
byte c = (byte)(b[offset++] & 0x7f);
len--;
if (isCaseInsensitive())
c = (byte)StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0)
{
t = _tree[row + EQ];
if (t == 0)
break loop;
// if this node is a match, recurse to remember
if (_key[t] != null)
{
node = t;
V better = getBest(t, b, offset, len);
if (better != null)
return better;
}
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
break loop;
}
}
return _value[node];
}
private V getBest(int t, ByteBuffer b, int offset, int len)
{
int node = t;
int o = offset + b.position();
loop:
for (int i = 0; i < len; i++)
{
byte c = (byte)(b.get(o + i) & 0x7f);
if (isCaseInsensitive())
c = (byte)StringUtil.lowercases[c];
while (true)
{
int row = ROW_SIZE * t;
char n = _tree[row];
int diff = n - c;
if (diff == 0)
{
t = _tree[row + EQ];
if (t == 0)
break loop;
// if this node is a match, recurse to remember
if (_key[t] != null)
{
node = t;
V best = getBest(t, b, offset + i + 1, len - i - 1);
if (best != null)
return best;
}
break;
}
t = _tree[row + hilo(diff)];
if (t == 0)
break loop;
}
}
return _value[node];
}
@Override
public String toString()
{
StringBuilder buf = new StringBuilder();
for (int r = 0; r <= _rows; r++)
{
if (_key[r] != null && _value[r] != null)
{
buf.append(',');
buf.append(_key[r]);
buf.append('=');
buf.append(_value[r].toString());
}
}
if (buf.length() == 0)
return "{}";
buf.setCharAt(0, '{');
buf.append('}');
return buf.toString();
}
@Override
public Set<String> keySet()
{
Set<String> keys = new HashSet<>();
for (int r = 0; r <= _rows; r++)
{
if (_key[r] != null && _value[r] != null)
keys.add(_key[r]);
}
return keys;
}
public int size()
{
int s = 0;
for (int r = 0; r <= _rows; r++)
{
if (_key[r] != null && _value[r] != null)
s++;
}
return s;
}
public boolean isEmpty()
{
for (int r = 0; r <= _rows; r++)
{
if (_key[r] != null && _value[r] != null)
return false;
}
return true;
}
public Set<Map.Entry<String, V>> entrySet()
{
Set<Map.Entry<String, V>> entries = new HashSet<>();
for (int r = 0; r <= _rows; r++)
{
if (_key[r] != null && _value[r] != null)
entries.add(new AbstractMap.SimpleEntry<>(_key[r], _value[r]));
}
return entries;
}
@Override
public boolean isFull()
{
return _rows + 1 == _key.length;
}
public static int hilo(int diff)
{
// branchless equivalent to return ((diff<0)?LO:HI);
// return 3+2*((diff&Integer.MIN_VALUE)>>Integer.SIZE-1);
return 1 + (diff | Integer.MAX_VALUE) / (Integer.MAX_VALUE / 2);
}
public void dump()
{
for (int r = 0; r < _rows; r++)
{
char c = _tree[r * ROW_SIZE + 0];
System.err.printf("%4d [%s,%d,%d,%d] '%s':%s%n",
r,
(c < ' ' || c > 127) ? ("" + (int)c) : "'" + c + "'",
(int)_tree[r * ROW_SIZE + LO],
(int)_tree[r * ROW_SIZE + EQ],
(int)_tree[r * ROW_SIZE + HI],
_key[r],
_value[r]);
}
}
public static class Growing<V> implements Trie<V>
{
private final int _growby;
private ArrayTernaryTrie<V> _trie;
public Growing()
{
this(1024, 1024);
}
public Growing(int capacity, int growby)
{
_growby = growby;
_trie = new ArrayTernaryTrie<>(capacity);
}
public Growing(boolean insensitive, int capacity, int growby)
{
_growby = growby;
_trie = new ArrayTernaryTrie<>(insensitive, capacity);
}
@Override
public boolean put(V v)
{
return put(v.toString(), v);
}
@Override
public int hashCode()
{
return _trie.hashCode();
}
@Override
public V remove(String s)
{
return _trie.remove(s);
}
@Override
public V get(String s)
{
return _trie.get(s);
}
@Override
public V get(ByteBuffer b)
{
return _trie.get(b);
}
@Override
public V getBest(byte[] b, int offset, int len)
{
return _trie.getBest(b, offset, len);
}
@Override
public boolean isCaseInsensitive()
{
return _trie.isCaseInsensitive();
}
@Override
public boolean equals(Object obj)
{
return _trie.equals(obj);
}
@Override
public void clear()
{
_trie.clear();
}
@Override
public boolean put(String s, V v)
{
boolean added = _trie.put(s, v);
while (!added && _growby > 0)
{
ArrayTernaryTrie<V> bigger = new ArrayTernaryTrie<>(_trie.isCaseInsensitive(), _trie._key.length + _growby);
for (Map.Entry<String, V> entry : _trie.entrySet())
{
bigger.put(entry.getKey(), entry.getValue());
}
_trie = bigger;
added = _trie.put(s, v);
}
return added;
}
@Override
public V get(String s, int offset, int len)
{
return _trie.get(s, offset, len);
}
@Override
public V get(ByteBuffer b, int offset, int len)
{
return _trie.get(b, offset, len);
}
@Override
public V getBest(String s)
{
return _trie.getBest(s);
}
@Override
public V getBest(String s, int offset, int length)
{
return _trie.getBest(s, offset, length);
}
@Override
public V getBest(ByteBuffer b, int offset, int len)
{
return _trie.getBest(b, offset, len);
}
@Override
public String toString()
{
return _trie.toString();
}
@Override
public Set<String> keySet()
{
return _trie.keySet();
}
@Override
public boolean isFull()
{
return false;
}
public void dump()
{
_trie.dump();
}
public boolean isEmpty()
{
return _trie.isEmpty();
}
public int size()
{
return _trie.size();
}
}
}