diff src/goodjava/util/CaseInsensitiveMap.java @ 1607:fa066aaa068c

nginx caching
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 30 Apr 2021 20:23:28 -0600
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/goodjava/util/CaseInsensitiveMap.java	Fri Apr 30 20:23:28 2021 -0600
@@ -0,0 +1,99 @@
+package goodjava.util;
+
+import java.util.Map;
+import java.util.AbstractMap;
+import java.util.Set;
+import java.util.AbstractSet;
+import java.util.Iterator;
+
+
+public final class CaseInsensitiveMap<V> extends AbstractMap<String,V> {
+
+	public static final class Value<V> {
+		private final String s;
+		private final V v;
+
+		private Value(String s,V v) {
+			this.s = s;
+			this.v = v;
+		}
+	}
+
+	private final Map<String,Value<V>> map;
+
+	public CaseInsensitiveMap(Map<String,Value<V>> map) {
+		this.map = map;
+	}
+
+	@Override public int size() {
+		return map.size();
+	}
+
+	@Override public boolean isEmpty() {
+		return map.isEmpty();
+	}
+
+	@Override public boolean containsKey(Object key) {
+		if( !(key instanceof String) )
+			return false;
+		String s = (String)key;
+		return map.containsKey(s.toLowerCase());
+	}
+
+	@Override public V get(Object key) {
+		if( !(key instanceof String) )
+			return null;
+		String s = (String)key;
+		Value<V> val = map.get(s.toLowerCase());
+		return val==null ? null : val.v;
+	}
+
+	@Override public V put(String key,V value) {
+		Value<V> val = map.put( key.toLowerCase(), new Value<V>(key,value) );
+		return val==null ? null : val.v;
+	}
+
+	@Override public V remove(Object key) {
+		if( !(key instanceof String) )
+			return null;
+		String s = (String)key;
+		Value<V> val = map.remove(s.toLowerCase());
+		return val==null ? null : val.v;
+	}
+
+	@Override public void clear() {
+		map.clear();
+	}
+
+	@Override public Set<Map.Entry<String,V>> entrySet() {
+		return new MySet();
+	}
+
+	private class MySet extends AbstractSet<Map.Entry<String,V>> {
+
+		@Override public int size() {
+			return CaseInsensitiveMap.this.size();
+		}
+
+		@Override public Iterator<Map.Entry<String,V>> iterator() {
+			return new MyIterator();
+		}
+	}
+
+	private class MyIterator implements Iterator<Map.Entry<String,V>> {
+		final Iterator<Map.Entry<String,Value<V>>> iter = map.entrySet().iterator();
+
+		@Override public Map.Entry<String,V> next() {
+			Value<V> val = iter.next().getValue();
+			return new AbstractMap.SimpleImmutableEntry<String,V>( val.s, val.v );
+		}
+
+		@Override public boolean hasNext() {
+			return iter.hasNext();
+		}
+
+		@Override public void remove() {
+			iter.remove();
+		}
+	}
+}