package com.wizzardo.http.http2.hpack;

/**
 * Created by wizzardo on 08.08.15.
 */
public class HpackReader {

    public static int encode(int i, byte[] bytes, int offsetBits) {
        int prefix = 8 - (offsetBits % 8);
        int maxPrefix = (1 << prefix) - 1;
        int index = offsetBits / 8;

        if (i < maxPrefix) {
            int a = bytes[index];
            a = a & (((1 << (8 - prefix)) - 1) << prefix);
            bytes[index] = (byte) (a | i);
            return offsetBits + prefix;
        }

        int a = bytes[index];
        bytes[index++] = (byte) (a | maxPrefix);

        i -= maxPrefix;
        while (i >= 128) {
            a = 128 + (i % 128);
            bytes[index++] = (byte) a;
            i /= 128;
        }

        bytes[index++] = (byte) i;

        return index * 8;
    }
}

@@ -815,11 +815,1006 @@
 8;%0A    %7D
+%0A%0A    public static IntDecodingResult decode(byte%5B%5D bytes, int offsetBits) %7B%0A        int prefix = 8 - (offsetBits %25 8);%0A        int maxPrefix = (1 %3C%3C prefix) - 1;%0A        int index = offsetBits / 8;%0A%0A        int i = bytes%5Bindex%5D & maxPrefix;%0A        if (i != maxPrefix)%0A            return new IntDecodingResult(i, (index + 1) * 8);%0A%0A        long l = maxPrefix;%0A        int a;%0A        index++;%0A%0A        int count = 0;%0A        do %7B%0A            a = bytes%5Bindex++%5D & 0xff;%0A            l += (a & 127) %3C%3C count;%0A            count += 7;%0A        %7D while ((a & 128) == 128);%0A%0A        if (count %3E 64)%0A            throw new IllegalStateException(%22can not decode numbers with length %3E 64 bits%22);%0A%0A        return new IntDecodingResult(l, index * 8);%0A    %7D%0A%0A    public static class IntDecodingResult %7B%0A        public final long value;%0A        public final int offset;%0A%0A        public IntDecodingResult(long value, int offset) %7B%0A            this.value = value;%0A            this.offset = offset;%0A        %7D%0A    %7D
 %0A%7D%0A

add decoding