Created
February 24, 2018 23:39
-
-
Save DarkSeraphim/7a626e6fafd72b5417b0376efe26528d to your computer and use it in GitHub Desktop.
BitBuffer v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class BitBuffer { | |
| private ByteBuffer buffer; | |
| private int readByteIndex; | |
| private int readBitIndex; | |
| private List<ToLongBiFunction<ByteBuf, Integer>> readFunctions = Arrays.asList( | |
| (buf, index) -> buf.readByte(index), // 1 byte | |
| (buf, index) -> buf.readShort(index), // 2 bytes | |
| (buf, index) -> buf.readInt(index), // 3 bytes | |
| (buf, index) -> buf.readInt(index), // 4 bytes | |
| (buf, index) -> buf.readLong(index), // 5 bytes | |
| (buf, index) -> buf.readLong(index), // 6 bytes | |
| (buf, index) -> buf.readLong(index), // 7 bytes | |
| (buf, index) -> buf.readLong(index) // 8 bytes | |
| ); | |
| private static final int[] MASK = { | |
| 0b00000001, | |
| 0b00000011, | |
| 0b00000111, | |
| 0b00001111, | |
| 0b00011111, | |
| 0b00111111, | |
| 0b01111111, | |
| 0b11111111, | |
| }; | |
| public long readBits(int bitSize) { | |
| // TODO: check capacity | |
| int size = (int) Math.ceil(bitSize / 8.0); | |
| long data = readFunctions.get(size - 1).apply(buffer); | |
| if (readBitIndex > 0) { // O shat, we have overlap | |
| data >>= readBitIndex; // Scrap those damn bytes | |
| // Max overflow is one byte | |
| long last = buffer.readByte(); | |
| last &= MASK[readBitIndex]; | |
| last <<= (bitSize - readBitIndex); | |
| data |= last; | |
| } | |
| readByteIndex += (bitSize / 8); | |
| readBitIndex += (bitSize % 8); | |
| if (readBitIndex >= 8) { | |
| readBitIndex -= 8; | |
| readByteIndex++; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment