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 * $Id: $
12 *******************************************************************************/
13package org.jacoco.core.data;
14
15import java.io.DataInputStream;
16import java.io.IOException;
17import java.io.InputStream;
18
19/**
20 * Additional data input methods for compact storage of data structures.
21 *
22 * @see CompactDataOutput
23 * @author Marc R. Hoffmann
24 * @version $Revision: $
25 */
26public class CompactDataInput extends DataInputStream {
27
28 /**
29 * Creates a new {@link CompactDataInput} that uses the specified underlying
30 * input stream.
31 *
32 * @param in
33 * underlying input stream
34 */
35 public CompactDataInput(final InputStream in) {
36 super(in);
37 }
38
39 /**
40 * Reads a variable length representation of an integer value.
41 *
42 * @return read value
43 * @throws IOException
44 * might be thrown by the underlying stream
45 */
46 public int readVarInt() throws IOException {
47 final int value = 0xFF & readByte();
48 if ((value & 0x80) == 0) {
49 return value;
50 }
51 return (value & 0x7F) | (readVarInt() << 7);
52 }
53
54 private int booleanBuffer = 0;
55
56 private int booleanBufferSize = 0;
57
58 /**
59 * Reads a boolean value. Internally a sequence of boolean values is packed
60 * into single bits. After the last boolean value has been read
61 * {@link #finishPackedBoolean()} has to be called.
62 *
63 * @return boolean value
64 * @throws IOException
65 */
66 public boolean readPackedBoolean() throws IOException {
67 if (booleanBufferSize == 0) {
68 booleanBuffer = readByte();
69 booleanBufferSize = 8;
70 }
71 final boolean value = (booleanBuffer & 0x01) != 0;
72 booleanBuffer >>>= 1;
73 booleanBufferSize--;
74 return value;
75 }
76
77 /**
78 * Finalizes the input of a sequence of packed boolean values.
79 *
80 * @throws IOException
81 */
82 public void finishPackedBoolean() throws IOException {
83 booleanBufferSize = 0;
84 }
85
86}