View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.commons.compress.archivers.zip;
21  
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.nio.ByteOrder;
25  
26  import org.apache.commons.compress.utils.BitInputStream;
27  
28  /**
29   * Iterates over the bits of an InputStream. For each byte the bits are read from the right to the left.
30   *
31   * @since 1.7
32   */
33  final class BitStream extends BitInputStream {
34  
35      BitStream(final InputStream in) {
36          super(in, ByteOrder.LITTLE_ENDIAN);
37      }
38  
39      /**
40       * Returns the next bit.
41       *
42       * @return The next bit (0 or 1) or -1 if the end of the stream has been reached
43       * @throws IOException on error.
44       */
45      int nextBit() throws IOException {
46          return (int) readBits(1);
47      }
48  
49      /**
50       * Returns the integer value formed by the n next bits (up to 8 bits).
51       *
52       * @param n the number of bits read (up to 8)
53       * @return The value formed by the n bits, or -1 if the end of the stream has been reached
54       * @throws IOException on error.
55       */
56      long nextBits(final int n) throws IOException {
57          if (n < 0 || n > 8) {
58              throw new IOException("Trying to read " + n + " bits, at most 8 are allowed");
59          }
60          return readBits(n);
61      }
62  
63      int nextByte() throws IOException {
64          return (int) readBits(8);
65      }
66  }