BitStream.java

  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. package org.apache.commons.compress.archivers.zip;

  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.nio.ByteOrder;

  23. import org.apache.commons.compress.utils.BitInputStream;

  24. /**
  25.  * Iterates over the bits of an InputStream. For each byte the bits are read from the right to the left.
  26.  *
  27.  * @since 1.7
  28.  */
  29. final class BitStream extends BitInputStream {

  30.     BitStream(final InputStream in) {
  31.         super(in, ByteOrder.LITTLE_ENDIAN);
  32.     }

  33.     /**
  34.      * Returns the next bit.
  35.      *
  36.      * @return The next bit (0 or 1) or -1 if the end of the stream has been reached
  37.      * @throws IOException on error.
  38.      */
  39.     int nextBit() throws IOException {
  40.         return (int) readBits(1);
  41.     }

  42.     /**
  43.      * Returns the integer value formed by the n next bits (up to 8 bits).
  44.      *
  45.      * @param n the number of bits read (up to 8)
  46.      * @return The value formed by the n bits, or -1 if the end of the stream has been reached
  47.      * @throws IOException on error.
  48.      */
  49.     long nextBits(final int n) throws IOException {
  50.         if (n < 0 || n > 8) {
  51.             throw new IOException("Trying to read " + n + " bits, at most 8 are allowed");
  52.         }
  53.         return readBits(n);
  54.     }

  55.     int nextByte() throws IOException {
  56.         return (int) readBits(8);
  57.     }
  58. }