CompactDataOutput.java
1/*******************************************************************************
2 * Copyright (c) 2009 Mountainminds GmbH & Co. KG and others
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.DataOutputStream;
16import java.io.IOException;
17import java.io.OutputStream;
18
19/**
20 * Additional data output methods for compact storage of data structures.
21 *
22 * @see CompactDataOutput
23 * @author Marc R. Hoffmann
24 * @version $Revision: $
25 */
26public class CompactDataOutput extends DataOutputStream {
27
28 /**
29 * Creates a new {@link CompactDataOutput} instance that writes data to the
30 * specified underlying output stream
31 *
32 * @param out
33 * underlying output stream
34 */
35 public CompactDataOutput(final OutputStream out) {
36 super(out);
37 }
38
39 /**
40 * Writes a variable length representation of an integer value that reduces
41 * the number of written bytes for small positive values. Depends on the
42 * given value 1 to 5 bytes will be written to the underlying stream.
43 *
44 * @param value
45 * value to write
46 * @throws IOException
47 */
48 public void writeVarInt(final int value) throws IOException {
49 if ((value & 0xFFFFFF80) == 0) {
50 writeByte(value);
51 } else {
52 writeByte(0x80 | (value & 0x7F));
53 writeVarInt(value >>> 7);
54 }
55 }
56
57 private int booleanBuffer = 0;
58
59 private int booleanBufferSize = 0;
60
61 /**
62 * Writes a boolean value. Internally a sequence of boolean values is packed
63 * into single bits. After the last boolean value has been written
64 * {@link #finishPackedBoolean()} has to be called.
65 *
66 * @param value
67 * boolean value
68 * @throws IOException
69 */
70 public void writePackedBoolean(final boolean value) throws IOException {
71 if (value) {
72 booleanBuffer |= 0x01 << booleanBufferSize;
73 }
74 if (++booleanBufferSize == 8) {
75 finishPackedBoolean();
76 }
77 }
78
79 /**
80 * Finalizes the output of a sequence of packed boolean values.
81 *
82 * @throws IOException
83 */
84 public void finishPackedBoolean() throws IOException {
85 if (booleanBufferSize > 0) {
86 writeByte(booleanBuffer);
87 booleanBuffer = 0;
88 booleanBufferSize = 0;
89 }
90 }
91
92}