Debian Codegraph @

src/tools/org/h2/dev/cluster/ShardedMap.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.cluster;
7
8 import java.util.AbstractMap;
9 import java.util.AbstractSet;
10 import java.util.Arrays;
11 import java.util.Iterator;
12 import java.util.Map;
13 import java.util.NoSuchElementException;
14 import java.util.Set;
15 import org.h2.mvstore.DataUtils;
16 import org.h2.mvstore.type.DataType;
17 import org.h2.mvstore.type.ObjectDataType;
18
19 /**
20 * A sharded map. It is typically split into multiple sub-maps that don't have
21 * overlapping keys.
22 *
23 * @param <K> the key type
24 * @param <V> the value type
25 */
26 public class ShardedMap<K, V> extends AbstractMap<K, V> {
27
28 private final DataType<Object> keyType;
29
30 /**
31 * The shards. Each shard has a minimum and a maximum key (null for no
32 * limit). Key ranges are ascending but can overlap, in which case entries
33 * may be stored in multiple maps. If that is the case, for read operations,
34 * the entry in the first map is used, and for write operations, the changes
35 * are applied to all maps within the range.
36 */
37 private Shard<K, V>[] shards;
38
39 public ShardedMap() {
40 this(new ObjectDataType());
41 }
42
43 @SuppressWarnings("unchecked")
44 public ShardedMap(DataType keyType) {
45 this.keyType = keyType;
46 shards = new Shard[0];
47 }
48
49 /**
50 * Get the size of the map.
51 *
52 * @param map the map
53 * @return the size
54 */
55 static long getSize(Map<?, ?> map) {
56 if (map instanceof LargeMap) {
57 return ((LargeMap) map).sizeAsLong();
58 }
59 return map.size();
60 }
61
62 /**
63 * Add the given shard.
64 *
65 * @param map the map
66 * @param min the lowest key, or null if no limit
67 * @param max the highest key, or null if no limit
68 */
69 public void addMap(Map<K, V> map, K min, K max) {
70 if (min != null && max != null && keyType.compare(min, max) > 0) {
71 DataUtils.newIllegalArgumentException("Invalid range: {0} .. {1}", min, max);
72 }
73 int len = shards.length + 1;
74 Shard<K, V>[] newShards = Arrays.copyOf(shards, len);
75 Shard<K, V> newShard = new Shard<>();
76 newShard.map = map;
77 newShard.minIncluding = min;
78 newShard.maxExcluding = max;
79 newShards[len - 1] = newShard;
80 shards = newShards;
81 }
82
83 private boolean isInRange(K key, Shard<K, V> shard) {
84 if (shard.minIncluding != null) {
85 if (keyType.compare(key, shard.minIncluding) < 0) {
86 return false;
87 }
88 }
89 if (shard.maxExcluding != null) {
90 if (keyType.compare(key, shard.maxExcluding) >= 0) {
91 return false;
92 }
93 }
94 return true;
95 }
96
97 @Override
98 public int size() {
99 long size = sizeAsLong();
100 return size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
101 }
102
103 /**
104 * The size of the map.
105 *
106 * @return the size
107 */
108 public long sizeAsLong() {
109 Shard<K, V>[] copy = shards;
110 for (Shard<K, V> s : copy) {
111 if (s.minIncluding == null && s.maxExcluding == null) {
112 return getSize(s.map);
113 }
114 }
115 if (isSimpleSplit(copy)) {
116 long size = 0;
117 for (Shard<K, V> s : copy) {
118 size += getSize(s.map);
119 }
120 return size;
121 }
122 return -1;
123 }
124
125 private boolean isSimpleSplit(Shard<K, V>[] shards) {
126 K last = null;
127 for (int i = 0; i < shards.length; i++) {
128 Shard<K, V> s = shards[i];
129 if (last == null) {
130 if (s.minIncluding != null) {
131 return false;
132 }
133 } else if (keyType.compare(last, s.minIncluding) != 0) {
134 return false;
135 }
136 if (s.maxExcluding == null) {
137 return i == shards.length - 1;
138 }
139 last = s.maxExcluding;
140 }
141 return last == null;
142 }
143
144 @Override
145 public V put(K key, V value) {
146 V result = null;
147 Shard<K, V>[] copy = shards;
148 for (Shard<K, V> s : copy) {
149 if (isInRange(key, s)) {
150 V r = s.map.put(key, value);
151 if (result == null) {
152 result = r;
153 }
154 }
155 }
156 return result;
157 }
158
159 @Override
160 public V get(Object key) {
161 @SuppressWarnings("unchecked")
162 K k = (K) key;
163 Shard<K, V>[] copy = shards;
164 for (Shard<K, V> s : copy) {
165 if (isInRange(k, s)) {
166 return s.map.get(k);
167 }
168 }
169 return null;
170 }
171
172 @Override
173 public Set<Entry<K, V>> entrySet() {
174 Shard<K, V>[] copy = shards;
175 for (Shard<K, V> s : copy) {
176 if (s.minIncluding == null && s.maxExcluding == null) {
177 return s.map.entrySet();
178 }
179 }
180 if (isSimpleSplit(copy)) {
181 return new CombinedSet<>(size(), copy);
182 }
183 return null;
184 }
185
186 /**
187 * A subset of a map.
188 *
189 * @param <K> the key type
190 * @param <V> the value type
191 */
192 static class Shard<K, V> {
193
194 /**
195 * The lowest key, or null if no limit.
196 */
197 K minIncluding;
198
199 /**
200 * A key higher than the highest key, or null if no limit.
201 */
202 K maxExcluding;
203
204 /**
205 * The backing map.
206 */
207 Map<K, V> map;
208
209 @Override
210 public String toString() {
211 StringBuilder buff = new StringBuilder();
212 if (minIncluding != null) {
213 buff.append('[').append(minIncluding);
214 }
215 buff.append("..");
216 if (maxExcluding != null) {
217 buff.append(maxExcluding).append(')');
218 }
219 return buff.toString();
220 }
221
222 }
223
224 /**
225 * A combination of multiple sets.
226 *
227 * @param <K> the key type
228 * @param <V> the value type
229 */
230 private static class CombinedSet<K, V> extends AbstractSet<Entry<K, V>> {
231
232 final int size;
233 final Shard<K, V>[] shards;
234
235 CombinedSet(int size, Shard<K, V>[] shards) {
236 this.size = size;
237 this.shards = shards;
238 }
239
240 @Override
241 public Iterator<Entry<K, V>> iterator() {
242 return new Iterator<Entry<K, V>>() {
243
244 boolean init;
245 Entry<K, V> current;
246 Iterator<Entry<K, V>> currentIterator;
247 int shardIndex;
248
249 private void fetchNext() {
250 while (currentIterator == null || !currentIterator.hasNext()) {
251 if (shardIndex >= shards.length) {
252 current = null;
253 return;
254 }
255 currentIterator = shards[shardIndex++].map.entrySet().iterator();
256 }
257 current = currentIterator.next();
258 }
259
260 @Override
261 public boolean hasNext() {
262 if (!init) {
263 fetchNext();
264 init = true;
265 }
266 return current != null;
267 }
268
269 @Override
270 public Entry<K, V> next() {
271 if (!hasNext()) {
272 throw new NoSuchElementException();
273 }
274 Entry<K, V> e = current;
275 fetchNext();
276 return e;
277 }
278
279 };
280 }
281
282 @Override
283 public int size() {
284 return size;
285 }
286
287 }
288
289 /**
290 * A large map.
291 */
292 public interface LargeMap {
293
294 /**
295 * The size of the map.
296 *
297 * @return the size
298 */
299 long sizeAsLong();
300 }
301
302 /**
303 * A map that can efficiently return the index of a key, and the key at a
304 * given index.
305 */
306 public interface CountedMap<K, V> {
307
308 /**
309 * Get the key at the given index.
310 *
311 * @param index the index
312 * @return the key
313 */
314 K getKey(long index);
315
316 /**
317 * Get the index of the given key in the map.
318 * <p>
319 * If the key was found, the returned value is the index in the key
320 * array. If not found, the returned value is negative, where -1 means
321 * the provided key is smaller than any keys. See also
322 * Arrays.binarySearch.
323 *
324 * @param key the key
325 * @return the index
326 */
327 long getKeyIndex(K key);
328 }
329
330 }