LittleEndianBinaryInputStream.java

/*
 * Copyright (c) 2016, Stein Eldar Johnsen
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * IO-Optimized binary reader using little-endian integer encoding.
 */
public class LittleEndianBinaryInputStream extends BinaryInputStream {
    /**
     * Create a little endian binary input stream.
     *
     * @param in Input stream to read data from.
     */
    public LittleEndianBinaryInputStream(InputStream in) {
        super(in);
    }

    @Override
    protected int unshift2bytes(int b1, int b2) {
        return (b1 | b2 << 8);
    }

    @Override
    protected int unshift3bytes(int b1, int b2, int b3) {
        return (b1 | b2 << 8 | b3 << 16);
    }

    @Override
    protected int unshift4bytes(int b1, int b2, int b3, int b4) {
        return (b1 | b2 << 8 | b3 << 16 | b4 << 24);
    }

    @Override
    protected long unshift8bytes(long b1, long b2, long b3, long b4, long b5, long b6, long b7, long b8) {
        return (b1 | b2 << 8 | b3 << 16 | b4 << 24 | b5 << 32 | b6 << 40 | b7 << 48 | b8 << 56);
    }

    @Override
    protected long unshiftNBytes(byte[] bytes) {
        long value = 0;
        for (int i = bytes.length - 1; i >= 0; --i) {
            value <<= 8;
            value |= (bytes[i] & 0xFF);
        }
        return value;
    }

    @Override
    protected int internalReadIntBase128(int i) throws IOException {
        boolean c = (i & 0x80) > 0;
        int out = (i & 0x7f);

        int shift = 0;
        while (c) {
            shift += 7;
            i = expectUInt8();
            c = (i & 0x80) > 0;
            out |= ((i & 0x7f) << shift);
        }
        return out;
    }

    @Override
    protected long internalReadLongBase128(int i) throws IOException {
        boolean c = (i & 0x80) > 0;
        long out = (i & 0x7f);

        int shift = 0;
        while (c) {
            shift += 7;
            i = expectUInt8();
            c = (i & 0x80) > 0;
            out |= ((long) i & 0x7f) << shift;
        }
        return out;
    }
}