1 | package org.armedbear.lisp; |
---|
2 | |
---|
3 | import java.lang.reflect.Array; |
---|
4 | import java.util.ArrayList; |
---|
5 | import java.util.Arrays; |
---|
6 | import java.util.Collection; |
---|
7 | import java.util.HashMap; |
---|
8 | import java.util.Iterator; |
---|
9 | import java.util.List; |
---|
10 | import java.util.Map; |
---|
11 | import java.util.Set; |
---|
12 | |
---|
13 | public class CharHashMap<T> { |
---|
14 | |
---|
15 | final public T[] constants; |
---|
16 | final public T NULL; |
---|
17 | final static int CACHE_SIZE = 256; |
---|
18 | final HashMap<Character, T> backing; |
---|
19 | |
---|
20 | @SuppressWarnings("unchecked") |
---|
21 | public CharHashMap(Class componentType, T def) { |
---|
22 | NULL = def; |
---|
23 | constants = (T[]) Array.newInstance(componentType, CACHE_SIZE); |
---|
24 | Arrays.fill(constants, NULL); |
---|
25 | backing = new HashMap<Character, T>(); |
---|
26 | } |
---|
27 | |
---|
28 | @Override |
---|
29 | public Object clone() { |
---|
30 | CharHashMap<T> n = new CharHashMap<T>(constants.getClass().getComponentType(),NULL); |
---|
31 | System.arraycopy(constants,0, n.constants,0,CACHE_SIZE); |
---|
32 | n.backing.putAll(backing); |
---|
33 | return n; |
---|
34 | } |
---|
35 | |
---|
36 | public T get(char key) { |
---|
37 | if (key<CACHE_SIZE) return constants[key]; |
---|
38 | T value = backing.get(key); |
---|
39 | return (value==null) ? NULL:value; |
---|
40 | } |
---|
41 | |
---|
42 | public void clear() { |
---|
43 | Arrays.fill(constants,NULL); |
---|
44 | backing.clear(); |
---|
45 | } |
---|
46 | |
---|
47 | public T put(char key, T value) { |
---|
48 | if (key<CACHE_SIZE) { |
---|
49 | T old = constants[key]; |
---|
50 | constants[key] = value; |
---|
51 | return old; |
---|
52 | } |
---|
53 | else return backing.put(key, value); |
---|
54 | } |
---|
55 | |
---|
56 | public Iterator<Character> getCharIterator() { |
---|
57 | return new Iterator<Character>() { |
---|
58 | final Iterator<Character> carIt = backing.keySet().iterator(); |
---|
59 | int charNum = -1; |
---|
60 | public boolean hasNext() { |
---|
61 | if ( charNum<CACHE_SIZE) return true; |
---|
62 | return carIt.hasNext(); |
---|
63 | } |
---|
64 | public Character next() { |
---|
65 | if ( charNum<CACHE_SIZE) return (char)++charNum; |
---|
66 | return carIt.next(); |
---|
67 | } |
---|
68 | public void remove() { |
---|
69 | throw new UnsupportedOperationException(); |
---|
70 | } |
---|
71 | |
---|
72 | }; |
---|
73 | } |
---|
74 | } |
---|