BaseNCodecInputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.codec.binary;

  18. import static org.apache.commons.codec.binary.BaseNCodec.EOF;

  19. import java.io.FilterInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;

  22. import org.apache.commons.codec.binary.BaseNCodec.Context;

  23. /**
  24.  * Abstract superclass for Base-N input streams.
  25.  *
  26.  * @since 1.5
  27.  * @version $Id: BaseNCodecInputStream.java 1429868 2013-01-07 16:08:05Z ggregory $
  28.  */
  29. public class BaseNCodecInputStream extends FilterInputStream {

  30.     private final BaseNCodec baseNCodec;

  31.     private final boolean doEncode;

  32.     private final byte[] singleByte = new byte[1];

  33.     private final Context context = new Context();

  34.     protected BaseNCodecInputStream(final InputStream in, final BaseNCodec baseNCodec, final boolean doEncode) {
  35.         super(in);
  36.         this.doEncode = doEncode;
  37.         this.baseNCodec = baseNCodec;
  38.     }

  39.     /**
  40.      * {@inheritDoc}
  41.      *
  42.      * @return <code>0</code> if the {@link InputStream} has reached <code>EOF</code>,
  43.      * <code>1</code> otherwise
  44.      * @since 1.7
  45.      */
  46.     @Override
  47.     public int available() throws IOException {
  48.         // Note: the logic is similar to the InflaterInputStream:
  49.         //       as long as we have not reached EOF, indicate that there is more
  50.         //       data available. As we do not know for sure how much data is left,
  51.         //       just return 1 as a safe guess.

  52.         return context.eof ? 0 : 1;
  53.     }

  54.     /**
  55.      * Marks the current position in this input stream.
  56.      * <p>The {@link #mark} method of {@link BaseNCodecInputStream} does nothing.</p>
  57.      *
  58.      * @param readLimit the maximum limit of bytes that can be read before the mark position becomes invalid.
  59.      * @since 1.7
  60.      */
  61.     @Override
  62.     public synchronized void mark(final int readLimit) {
  63.     }

  64.     /**
  65.      * {@inheritDoc}
  66.      *
  67.      * @return always returns <code>false</code>
  68.      */
  69.     @Override
  70.     public boolean markSupported() {
  71.         return false; // not an easy job to support marks
  72.     }

  73.     /**
  74.      * Reads one <code>byte</code> from this input stream.
  75.      *
  76.      * @return the byte as an integer in the range 0 to 255. Returns -1 if EOF has been reached.
  77.      * @throws IOException
  78.      *             if an I/O error occurs.
  79.      */
  80.     @Override
  81.     public int read() throws IOException {
  82.         int r = read(singleByte, 0, 1);
  83.         while (r == 0) {
  84.             r = read(singleByte, 0, 1);
  85.         }
  86.         if (r > 0) {
  87.             final byte b = singleByte[0];
  88.             return b < 0 ? 256 + b : b;
  89.         }
  90.         return EOF;
  91.     }

  92.     /**
  93.      * Attempts to read <code>len</code> bytes into the specified <code>b</code> array starting at <code>offset</code>
  94.      * from this InputStream.
  95.      *
  96.      * @param b
  97.      *            destination byte array
  98.      * @param offset
  99.      *            where to start writing the bytes
  100.      * @param len
  101.      *            maximum number of bytes to read
  102.      *
  103.      * @return number of bytes read
  104.      * @throws IOException
  105.      *             if an I/O error occurs.
  106.      * @throws NullPointerException
  107.      *             if the byte array parameter is null
  108.      * @throws IndexOutOfBoundsException
  109.      *             if offset, len or buffer size are invalid
  110.      */
  111.     @Override
  112.     public int read(final byte b[], final int offset, final int len) throws IOException {
  113.         if (b == null) {
  114.             throw new NullPointerException();
  115.         } else if (offset < 0 || len < 0) {
  116.             throw new IndexOutOfBoundsException();
  117.         } else if (offset > b.length || offset + len > b.length) {
  118.             throw new IndexOutOfBoundsException();
  119.         } else if (len == 0) {
  120.             return 0;
  121.         } else {
  122.             int readLen = 0;
  123.             /*
  124.              Rationale for while-loop on (readLen == 0):
  125.              -----
  126.              Base32.readResults() usually returns > 0 or EOF (-1).  In the
  127.              rare case where it returns 0, we just keep trying.

  128.              This is essentially an undocumented contract for InputStream
  129.              implementors that want their code to work properly with
  130.              java.io.InputStreamReader, since the latter hates it when
  131.              InputStream.read(byte[]) returns a zero.  Unfortunately our
  132.              readResults() call must return 0 if a large amount of the data
  133.              being decoded was non-base32, so this while-loop enables proper
  134.              interop with InputStreamReader for that scenario.
  135.              -----
  136.              This is a fix for CODEC-101
  137.             */
  138.             while (readLen == 0) {
  139.                 if (!baseNCodec.hasData(context)) {
  140.                     final byte[] buf = new byte[doEncode ? 4096 : 8192];
  141.                     final int c = in.read(buf);
  142.                     if (doEncode) {
  143.                         baseNCodec.encode(buf, 0, c, context);
  144.                     } else {
  145.                         baseNCodec.decode(buf, 0, c, context);
  146.                     }
  147.                 }
  148.                 readLen = baseNCodec.readResults(b, offset, len, context);
  149.             }
  150.             return readLen;
  151.         }
  152.     }

  153.     /**
  154.      * Repositions this stream to the position at the time the mark method was last called on this input stream.
  155.      * <p>
  156.      * The {@link #reset} method of {@link BaseNCodecInputStream} does nothing except throw an {@link IOException}.
  157.      *
  158.      * @throws IOException if this method is invoked
  159.      * @since 1.7
  160.      */
  161.     @Override
  162.     public synchronized void reset() throws IOException {
  163.         throw new IOException("mark/reset not supported");
  164.     }

  165.     /**
  166.      * {@inheritDoc}
  167.      *
  168.      * @throws IllegalArgumentException if the provided skip length is negative
  169.      * @since 1.7
  170.      */
  171.     @Override
  172.     public long skip(final long n) throws IOException {
  173.         if (n < 0) {
  174.             throw new IllegalArgumentException("Negative skip length: " + n);
  175.         }

  176.         // skip in chunks of 512 bytes
  177.         final byte[] b = new byte[512];
  178.         long todo = n;

  179.         while (todo > 0) {
  180.             int len = (int) Math.min(b.length, todo);
  181.             len = this.read(b, 0, len);
  182.             if (len == EOF) {
  183.                 break;
  184.             }
  185.             todo -= len;
  186.         }

  187.         return n - todo;
  188.     }
  189. }