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