| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
package com.drew.lang; |
| 22 |
|
| 23 |
import com.drew.lang.annotations.Nullable; |
| 24 |
|
| 25 |
import java.util.HashMap; |
| 26 |
import java.util.Map; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
public class ByteTrie<T> |
| 34 |
{ |
| 35 |
|
| 36 |
static class ByteTrieNode<T> |
| 37 |
{ |
| 38 |
private final Map<Byte, ByteTrieNode<T>> _children = new HashMap<Byte, ByteTrieNode<T>>(); |
| 39 |
private T _value = null; |
| 40 |
|
| 41 |
public void setValue(T value) |
| 42 |
{ |
| 43 |
if (_value != null) |
| 44 |
throw new RuntimeException("Value already set for this trie node"); |
| 45 |
_value = value; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
private final ByteTrieNode<T> _root = new ByteTrieNode<T>(); |
| 50 |
private int _maxDepth; |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
@Nullable |
| 58 |
public T find(byte[] bytes) |
| 59 |
{ |
| 60 |
return find(bytes, 0, bytes.length); |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
@Nullable |
| 69 |
public T find(byte[] bytes, int offset, int count) |
| 70 |
{ |
| 71 |
int maxIndex = offset + count; |
| 72 |
if (maxIndex > bytes.length) |
| 73 |
throw new IndexOutOfBoundsException(); |
| 74 |
|
| 75 |
ByteTrieNode<T> node = _root; |
| 76 |
T value = node._value; |
| 77 |
for (int i = offset; i < maxIndex; i++) { |
| 78 |
byte b = bytes[i]; |
| 79 |
ByteTrieNode<T> child = node._children.get(b); |
| 80 |
if (child == null) |
| 81 |
break; |
| 82 |
node = child; |
| 83 |
if (node._value != null) |
| 84 |
value = node._value; |
| 85 |
} |
| 86 |
return value; |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
public void addPath(T value, byte[]... parts) |
| 91 |
{ |
| 92 |
int depth = 0; |
| 93 |
ByteTrieNode<T> node = _root; |
| 94 |
for (byte[] part : parts) { |
| 95 |
for (byte b : part) { |
| 96 |
ByteTrieNode<T> child = node._children.get(b); |
| 97 |
if (child == null) { |
| 98 |
child = new ByteTrieNode<T>(); |
| 99 |
node._children.put(b, child); |
| 100 |
} |
| 101 |
node = child; |
| 102 |
depth++; |
| 103 |
} |
| 104 |
} |
| 105 |
if (depth == 0) |
| 106 |
throw new IllegalArgumentException("Parts must contain at least one byte."); |
| 107 |
node.setValue(value); |
| 108 |
_maxDepth = Math.max(_maxDepth, depth); |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
public void setDefaultValue(T defaultValue) |
| 113 |
{ |
| 114 |
_root.setValue(defaultValue); |
| 115 |
} |
| 116 |
|
| 117 |
|
| 118 |
public int getMaxDepth() |
| 119 |
{ |
| 120 |
return _maxDepth; |
| 121 |
} |
| 122 |
} |