package org.jcodings.util;
public final class BytesHash<V> extends Hash<V>{
public BytesHash() {
super();
}
public BytesHash(int size) {
super(size);
}
protected void init() {
head = new BytesHashEntry<V>();
}
public final static class BytesHashEntry<V> extends HashEntry<V> {
public final byte[]bytes;
public final int p;
public final int end;
public BytesHashEntry(int hash, HashEntry<V> next, V value, byte[]bytes, int p, int end, HashEntry<V> head) {
super(hash, next, value, head);
this.bytes = bytes;
this.p = p;
this.end = end;
}
public BytesHashEntry() {
super();
bytes = null;
p = end = 0;
}
public boolean equals(byte[]bytes, int p, int end) {
if (this.end - this.p != end - p) return false;
if (this.bytes == bytes) return true;
int q = this.p;
while (q < this.end) if (this.bytes[q++] != bytes[p++]) return false;
return true;
}
}
public static int hashCode(byte[]bytes, int p, int end) {
int key = 0;
while (p < end) key = ((key << 16) + (key << 6) - key) + (int)(bytes[p++]);
key = key + (key >> 5);
return key;
}
public V put(byte[]bytes, V value) {
return put(bytes, 0, bytes.length, value);
}
public V put(byte[]bytes, int p, int end, V value) {
checkResize();
int hash = hashValue(hashCode(bytes, p, end));
int i = bucketIndex(hash, table.length);
for (BytesHashEntry<V> entry = (BytesHashEntry<V>)table[i]; entry != null; entry = (BytesHashEntry<V>)entry.next) {
if (entry.hash == hash && entry.equals(bytes, p, end)) {
entry.value = value;
return value;
}
}
table[i] = new BytesHashEntry<V>(hash, table[i], value, bytes, p, end, head);
size++;
return null;
}
public void putDirect(byte[]bytes, V value) {
putDirect(bytes, 0, bytes.length, value);
}
public void putDirect(byte[]bytes, int p, int end, V value) {
checkResize();
final int hash = hashValue(hashCode(bytes, p, end));
final int i = bucketIndex(hash, table.length);
table[i] = new BytesHashEntry<V>(hash, table[i], value, bytes, p, end, head);
size++;
}
public V get(byte[]bytes) {
return get(bytes, 0, bytes.length);
}
public V get(byte[]bytes, int p, int end) {
int hash = hashValue(hashCode(bytes, p, end));
for (BytesHashEntry<V> entry = (BytesHashEntry<V>)table[bucketIndex(hash, table.length)]; entry != null; entry = (BytesHashEntry<V>)entry.next) {
if (entry.hash == hash && entry.equals(bytes, p, end)) return entry.value;
}
return null;
}
public V delete(byte[]bytes) {
return delete(bytes, 0, bytes.length);
}
public V delete(byte[]bytes, int p, int end) {
int hash = hashValue(hashCode(bytes, p, end));
int i = bucketIndex(hash, table.length);
BytesHashEntry<V> entry = (BytesHashEntry<V>)table[i];
if (entry == null) return null;
if (entry.hash == hash && entry.equals(bytes, p, end)) {
table[i] = entry.next;
size--;
entry.remove();
return entry.value;
}
for (; entry.next != null; entry = (BytesHashEntry<V>)entry.next) {
HashEntry<V> tmp = entry.next;
if (tmp.hash == hash && entry.equals(bytes, p, end)) {
entry.next = entry.next.next;
size--;
tmp.remove();
return tmp.value;
}
}
return null;
}
}