// 
// Decompiled by Procyon v0.6.0
// 

package ch.randelshofer.fastdoubleparser.bte;

import java.util.Iterator;
import java.util.Collection;

final class ByteToIntMap implements ByteDigitSet, ByteSet
{
    private Node[] table;
    
    public ByteToIntMap(final Collection<Character> chars) {
        this(chars.size());
        int i = 0;
        for (final char ch : chars) {
            if (ch > '\u007f') {
                throw new IllegalArgumentException("can not map to a single byte. ch=" + ch);
            }
            this.put((byte)ch, i++);
        }
    }
    
    @Override
    public boolean containsKey(final byte b) {
        return this.getOrDefault(b, -1) >= 0;
    }
    
    @Override
    public int toDigit(final byte ch) {
        return this.getOrDefault(ch, 10);
    }
    
    public ByteToIntMap(final int maxSize) {
        final int n = (-1 >>> Integer.numberOfLeadingZeros(maxSize * 2)) + 1;
        this.table = new Node[n];
    }
    
    public void put(final byte key, final int value) {
        final int index = this.getIndex(key);
        Node found = this.table[index];
        if (found == null) {
            this.table[index] = new Node(key, value);
        }
        else {
            while (found.next != null && found.key != key) {
                found = found.next;
            }
            if (found.key == key) {
                found.value = value;
            }
            else {
                found.next = new Node(key, value);
            }
        }
    }
    
    private int getIndex(final byte key) {
        return key & this.table.length - 1;
    }
    
    public int getOrDefault(final byte key, final int defaultValue) {
        final int index = this.getIndex(key);
        for (Node found = this.table[index]; found != null; found = found.next) {
            if (found.key == key) {
                return found.value;
            }
        }
        return defaultValue;
    }
    
    private static class Node
    {
        byte key;
        int value;
        Node next;
        
        public Node(final byte key, final int value) {
            this.key = key;
            this.value = value;
        }
    }
}
