CompactDataOutput.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.DataOutputStream;
   15import java.io.IOException;
   16import java.io.OutputStream;
   17
   18/**
   19 * Additional data output 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 CompactDataOutput extends DataOutputStream {
   26
   27    /**
   28     * Creates a new {@link CompactDataOutput} instance that writes data to the
   29     * specified underlying output stream
   30     * 
   31     * @param out
   32     *            underlying output stream
   33     */
   34    public CompactDataOutput(final OutputStream out) {
   35        super(out);
   36    }
   37
   38    /**
   39     * Writes a variable length representation of an integer value that reduces
   40     * the number of written bytes for small positive values. Depending on the
   41     * given value 1 to 5 bytes will be written to the underlying stream.
   42     * 
   43     * @param value
   44     *            value to write
   45     * @throws IOException
   46     */
   47    public void writeVarInt(final int value) throws IOException {
   48        if ((value & 0xFFFFFF80) == 0) {
   49            writeByte(value);
   50        } else {
   51            writeByte(0x80 | (value & 0x7F));
   52            writeVarInt(value >>> 7);
   53        }
   54    }
   55
   56    /**
   57     * Writes a boolean array. Internally a sequence of boolean values is packed
   58     * into single bits.
   59     * 
   60     * @param value
   61     *            boolean array
   62     * @throws IOException
   63     */
   64    public void writeBooleanArray(final boolean[] value) throws IOException {
   65        writeVarInt(value.length);
   66        int buffer = 0;
   67        int bufferSize = 0;
   68        for (final boolean b : value) {
   69            if (b) {
   70                buffer |= 0x01 << bufferSize;
   71            }
   72            if (++bufferSize == 8) {
   73                writeByte(buffer);
   74                buffer = 0;
   75                bufferSize = 0;
   76            }
   77        }
   78        if (bufferSize > 0) {
   79            writeByte(buffer);
   80        }
   81    }
   82
   83}