CompactDataInput.java

    1/*******************************************************************************
    2 * Copyright (c) 2009, 2010 Mountainminds GmbH & Co. KG and Contributors
    3 * All rights reserved. This program and the accompanying materials
    4 * are made available under the terms of the Eclipse Public License v1.0
    5 * which accompanies this distribution, and is available at
    6 * http://www.eclipse.org/legal/epl-v10.html
    7 *
    8 * Contributors:
    9 *    Marc R. Hoffmann - initial API and implementation
   10 *    
   11 *******************************************************************************/
   12package org.jacoco.core.data;
   13
   14import java.io.DataInputStream;
   15import java.io.IOException;
   16import java.io.InputStream;
   17
   18/**
   19 * Additional data input methods for compact storage of data structures.
   20 * 
   21 * @see CompactDataOutput
   22 * @author Marc R. Hoffmann
   23 * @version 0.4.1.20101007204400
   24 */
   25public class CompactDataInput extends DataInputStream {
   26
   27    /**
   28     * Creates a new {@link CompactDataInput} that uses the specified underlying
   29     * input stream.
   30     * 
   31     * @param in
   32     *            underlying input stream
   33     */
   34    public CompactDataInput(final InputStream in) {
   35        super(in);
   36    }
   37
   38    /**
   39     * Reads a variable length representation of an integer value.
   40     * 
   41     * @return read value
   42     * @throws IOException
   43     *             might be thrown by the underlying stream
   44     */
   45    public int readVarInt() throws IOException {
   46        final int value = 0xFF & readByte();
   47        if ((value & 0x80) == 0) {
   48            return value;
   49        }
   50        return (value & 0x7F) | (readVarInt() << 7);
   51    }
   52
   53    /**
   54     * Reads a boolean array.
   55     * 
   56     * @return boolean array
   57     * @throws IOException
   58     */
   59    public boolean[] readBooleanArray() throws IOException {
   60        final boolean[] value = new boolean[readVarInt()];
   61        int buffer = 0;
   62        for (int i = 0; i < value.length; i++) {
   63            if ((i % 8) == 0) {
   64                buffer = readByte();
   65            }
   66            value[i] = (buffer & 0x01) != 0;
   67            buffer >>>= 1;
   68        }
   69        return value;
   70    }
   71
   72}