001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkPositionIndex;
020import static com.google.common.base.Preconditions.checkPositionIndexes;
021import static java.lang.Math.max;
022import static java.lang.Math.min;
023
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.annotations.J2ktIncompatible;
026import com.google.common.math.IntMath;
027import com.google.errorprone.annotations.CanIgnoreReturnValue;
028import java.io.ByteArrayInputStream;
029import java.io.ByteArrayOutputStream;
030import java.io.DataInput;
031import java.io.DataInputStream;
032import java.io.DataOutput;
033import java.io.DataOutputStream;
034import java.io.EOFException;
035import java.io.FilterInputStream;
036import java.io.IOException;
037import java.io.InputStream;
038import java.io.OutputStream;
039import java.nio.ByteBuffer;
040import java.nio.channels.FileChannel;
041import java.nio.channels.ReadableByteChannel;
042import java.nio.channels.WritableByteChannel;
043import java.util.ArrayDeque;
044import java.util.Arrays;
045import java.util.Queue;
046import org.checkerframework.checker.nullness.qual.Nullable;
047
048/**
049 * Provides utility methods for working with byte arrays and I/O streams.
050 *
051 * @author Chris Nokleberg
052 * @author Colin Decker
053 * @since 1.0
054 */
055@J2ktIncompatible
056@GwtIncompatible
057public final class ByteStreams {
058
059  private static final int BUFFER_SIZE = 8192;
060
061  /** Creates a new byte array for buffering reads or writes. */
062  static byte[] createBuffer() {
063    return new byte[BUFFER_SIZE];
064  }
065
066  /**
067   * There are three methods to implement {@link FileChannel#transferTo(long, long,
068   * WritableByteChannel)}:
069   *
070   * <ol>
071   *   <li>Use sendfile(2) or equivalent. Requires that both the input channel and the output
072   *       channel have their own file descriptors. Generally this only happens when both channels
073   *       are files or sockets. This performs zero copies - the bytes never enter userspace.
074   *   <li>Use mmap(2) or equivalent. Requires that either the input channel or the output channel
075   *       have file descriptors. Bytes are copied from the file into a kernel buffer, then directly
076   *       into the other buffer (userspace). Note that if the file is very large, a naive
077   *       implementation will effectively put the whole file in memory. On many systems with paging
078   *       and virtual memory, this is not a problem - because it is mapped read-only, the kernel
079   *       can always page it to disk "for free". However, on systems where killing processes
080   *       happens all the time in normal conditions (i.e., android) the OS must make a tradeoff
081   *       between paging memory and killing other processes - so allocating a gigantic buffer and
082   *       then sequentially accessing it could result in other processes dying. This is solvable
083   *       via madvise(2), but that obviously doesn't exist in java.
084   *   <li>Ordinary copy. Kernel copies bytes into a kernel buffer, from a kernel buffer into a
085   *       userspace buffer (byte[] or ByteBuffer), then copies them from that buffer into the
086   *       destination channel.
087   * </ol>
088   *
089   * This value is intended to be large enough to make the overhead of system calls negligible,
090   * without being so large that it causes problems for systems with atypical memory management if
091   * approaches 2 or 3 are used.
092   */
093  private static final int ZERO_COPY_CHUNK_SIZE = 512 * 1024;
094
095  private ByteStreams() {}
096
097  /**
098   * Copies all bytes from the input stream to the output stream. Does not close or flush either
099   * stream.
100   *
101   * <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the
102   * equivalent {@link InputStream#transferTo} method instead.
103   *
104   * @param from the input stream to read from
105   * @param to the output stream to write to
106   * @return the number of bytes copied
107   * @throws IOException if an I/O error occurs
108   */
109  @CanIgnoreReturnValue
110  public static long copy(InputStream from, OutputStream to) throws IOException {
111    checkNotNull(from);
112    checkNotNull(to);
113    byte[] buf = createBuffer();
114    long total = 0;
115    while (true) {
116      int r = from.read(buf);
117      if (r == -1) {
118        break;
119      }
120      to.write(buf, 0, r);
121      total += r;
122    }
123    return total;
124  }
125
126  /**
127   * Copies all bytes from the readable channel to the writable channel. Does not close or flush
128   * either channel.
129   *
130   * @param from the readable channel to read from
131   * @param to the writable channel to write to
132   * @return the number of bytes copied
133   * @throws IOException if an I/O error occurs
134   */
135  @CanIgnoreReturnValue
136  public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException {
137    checkNotNull(from);
138    checkNotNull(to);
139    if (from instanceof FileChannel) {
140      FileChannel sourceChannel = (FileChannel) from;
141      long oldPosition = sourceChannel.position();
142      long position = oldPosition;
143      long copied;
144      do {
145        copied = sourceChannel.transferTo(position, ZERO_COPY_CHUNK_SIZE, to);
146        position += copied;
147        sourceChannel.position(position);
148      } while (copied > 0 || position < sourceChannel.size());
149      return position - oldPosition;
150    }
151
152    ByteBuffer buf = ByteBuffer.wrap(createBuffer());
153    long total = 0;
154    while (from.read(buf) != -1) {
155      Java8Compatibility.flip(buf);
156      while (buf.hasRemaining()) {
157        total += to.write(buf);
158      }
159      Java8Compatibility.clear(buf);
160    }
161    return total;
162  }
163
164  /** Max array length on JVM. */
165  private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8;
166
167  /** Large enough to never need to expand, given the geometric progression of buffer sizes. */
168  private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20;
169
170  /**
171   * Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have
172   * a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given
173   * input stream.
174   */
175  private static byte[] toByteArrayInternal(InputStream in, Queue<byte[]> bufs, int totalLen)
176      throws IOException {
177    // Roughly size to match what has been read already. Some file systems, such as procfs, return 0
178    // as their length. These files are very small, so it's wasteful to allocate an 8KB buffer.
179    int initialBufferSize = min(BUFFER_SIZE, max(128, Integer.highestOneBit(totalLen) * 2));
180    // Starting with an 8k buffer, double the size of each successive buffer. Smaller buffers
181    // quadruple in size until they reach 8k, to minimize the number of small reads for longer
182    // streams. Buffers are retained in a deque so that there's no copying between buffers while
183    // reading and so all of the bytes in each new allocated buffer are available for reading from
184    // the stream.
185    for (int bufSize = initialBufferSize;
186        totalLen < MAX_ARRAY_LEN;
187        bufSize = IntMath.saturatedMultiply(bufSize, bufSize < 4096 ? 4 : 2)) {
188      byte[] buf = new byte[min(bufSize, MAX_ARRAY_LEN - totalLen)];
189      bufs.add(buf);
190      int off = 0;
191      while (off < buf.length) {
192        // always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN
193        int r = in.read(buf, off, buf.length - off);
194        if (r == -1) {
195          return combineBuffers(bufs, totalLen);
196        }
197        off += r;
198        totalLen += r;
199      }
200    }
201
202    // read MAX_ARRAY_LEN bytes without seeing end of stream
203    if (in.read() == -1) {
204      // oh, there's the end of the stream
205      return combineBuffers(bufs, MAX_ARRAY_LEN);
206    } else {
207      throw new OutOfMemoryError("input is too large to fit in a byte array");
208    }
209  }
210
211  private static byte[] combineBuffers(Queue<byte[]> bufs, int totalLen) {
212    if (bufs.isEmpty()) {
213      return new byte[0];
214    }
215    byte[] result = bufs.remove();
216    if (result.length == totalLen) {
217      return result;
218    }
219    int remaining = totalLen - result.length;
220    result = Arrays.copyOf(result, totalLen);
221    while (remaining > 0) {
222      byte[] buf = bufs.remove();
223      int bytesToCopy = min(remaining, buf.length);
224      int resultOffset = totalLen - remaining;
225      System.arraycopy(buf, 0, result, resultOffset, bytesToCopy);
226      remaining -= bytesToCopy;
227    }
228    return result;
229  }
230
231  /**
232   * Reads all bytes from an input stream into a byte array. Does not close the stream.
233   *
234   * <p><b>Java 9+ users:</b> use {@code in#readAllBytes()} instead.
235   *
236   * @param in the input stream to read from
237   * @return a byte array containing all the bytes from the stream
238   * @throws IOException if an I/O error occurs
239   */
240  public static byte[] toByteArray(InputStream in) throws IOException {
241    checkNotNull(in);
242    return toByteArrayInternal(in, new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE), 0);
243  }
244
245  /**
246   * Reads all bytes from an input stream into a byte array. The given expected size is used to
247   * create an initial byte array, but if the actual number of bytes read from the stream differs,
248   * the correct result will be returned anyway.
249   */
250  static byte[] toByteArray(InputStream in, long expectedSize) throws IOException {
251    checkArgument(expectedSize >= 0, "expectedSize (%s) must be non-negative", expectedSize);
252    if (expectedSize > MAX_ARRAY_LEN) {
253      throw new OutOfMemoryError(expectedSize + " bytes is too large to fit in a byte array");
254    }
255
256    byte[] bytes = new byte[(int) expectedSize];
257    int remaining = (int) expectedSize;
258
259    while (remaining > 0) {
260      int off = (int) expectedSize - remaining;
261      int read = in.read(bytes, off, remaining);
262      if (read == -1) {
263        // end of stream before reading expectedSize bytes
264        // just return the bytes read so far
265        return Arrays.copyOf(bytes, off);
266      }
267      remaining -= read;
268    }
269
270    // bytes is now full
271    int b = in.read();
272    if (b == -1) {
273      return bytes;
274    }
275
276    // the stream was longer, so read the rest normally
277    Queue<byte[]> bufs = new ArrayDeque<>(TO_BYTE_ARRAY_DEQUE_SIZE + 2);
278    bufs.add(bytes);
279    bufs.add(new byte[] {(byte) b});
280    return toByteArrayInternal(in, bufs, bytes.length + 1);
281  }
282
283  /**
284   * Reads and discards data from the given {@code InputStream} until the end of the stream is
285   * reached. Returns the total number of bytes read. Does not close the stream.
286   *
287   * @since 20.0
288   */
289  @CanIgnoreReturnValue
290  public static long exhaust(InputStream in) throws IOException {
291    long total = 0;
292    long read;
293    byte[] buf = createBuffer();
294    while ((read = in.read(buf)) != -1) {
295      total += read;
296    }
297    return total;
298  }
299
300  /**
301   * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the
302   * beginning.
303   */
304  public static ByteArrayDataInput newDataInput(byte[] bytes) {
305    return newDataInput(new ByteArrayInputStream(bytes));
306  }
307
308  /**
309   * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array,
310   * starting at the given position.
311   *
312   * @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of
313   *     the array
314   */
315  public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
316    checkPositionIndex(start, bytes.length);
317    return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start));
318  }
319
320  /**
321   * Returns a new {@link ByteArrayDataInput} instance to read from the given {@code
322   * ByteArrayInputStream}. The given input stream is not reset before being read from by the
323   * returned {@code ByteArrayDataInput}.
324   *
325   * @since 17.0
326   */
327  public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) {
328    return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream));
329  }
330
331  private static class ByteArrayDataInputStream implements ByteArrayDataInput {
332    final DataInput input;
333
334    ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) {
335      this.input = new DataInputStream(byteArrayInputStream);
336    }
337
338    @Override
339    public void readFully(byte b[]) {
340      try {
341        input.readFully(b);
342      } catch (IOException e) {
343        throw new IllegalStateException(e);
344      }
345    }
346
347    @Override
348    public void readFully(byte b[], int off, int len) {
349      try {
350        input.readFully(b, off, len);
351      } catch (IOException e) {
352        throw new IllegalStateException(e);
353      }
354    }
355
356    @Override
357    public int skipBytes(int n) {
358      try {
359        return input.skipBytes(n);
360      } catch (IOException e) {
361        throw new IllegalStateException(e);
362      }
363    }
364
365    @Override
366    public boolean readBoolean() {
367      try {
368        return input.readBoolean();
369      } catch (IOException e) {
370        throw new IllegalStateException(e);
371      }
372    }
373
374    @Override
375    public byte readByte() {
376      try {
377        return input.readByte();
378      } catch (EOFException e) {
379        throw new IllegalStateException(e);
380      } catch (IOException impossible) {
381        throw new AssertionError(impossible);
382      }
383    }
384
385    @Override
386    public int readUnsignedByte() {
387      try {
388        return input.readUnsignedByte();
389      } catch (IOException e) {
390        throw new IllegalStateException(e);
391      }
392    }
393
394    @Override
395    public short readShort() {
396      try {
397        return input.readShort();
398      } catch (IOException e) {
399        throw new IllegalStateException(e);
400      }
401    }
402
403    @Override
404    public int readUnsignedShort() {
405      try {
406        return input.readUnsignedShort();
407      } catch (IOException e) {
408        throw new IllegalStateException(e);
409      }
410    }
411
412    @Override
413    public char readChar() {
414      try {
415        return input.readChar();
416      } catch (IOException e) {
417        throw new IllegalStateException(e);
418      }
419    }
420
421    @Override
422    public int readInt() {
423      try {
424        return input.readInt();
425      } catch (IOException e) {
426        throw new IllegalStateException(e);
427      }
428    }
429
430    @Override
431    public long readLong() {
432      try {
433        return input.readLong();
434      } catch (IOException e) {
435        throw new IllegalStateException(e);
436      }
437    }
438
439    @Override
440    public float readFloat() {
441      try {
442        return input.readFloat();
443      } catch (IOException e) {
444        throw new IllegalStateException(e);
445      }
446    }
447
448    @Override
449    public double readDouble() {
450      try {
451        return input.readDouble();
452      } catch (IOException e) {
453        throw new IllegalStateException(e);
454      }
455    }
456
457    @Override
458    public @Nullable String readLine() {
459      try {
460        return input.readLine();
461      } catch (IOException e) {
462        throw new IllegalStateException(e);
463      }
464    }
465
466    @Override
467    public String readUTF() {
468      try {
469        return input.readUTF();
470      } catch (IOException e) {
471        throw new IllegalStateException(e);
472      }
473    }
474  }
475
476  /** Returns a new {@link ByteArrayDataOutput} instance with a default size. */
477  public static ByteArrayDataOutput newDataOutput() {
478    return newDataOutput(new ByteArrayOutputStream());
479  }
480
481  /**
482   * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} bytes before
483   * resizing.
484   *
485   * @throws IllegalArgumentException if {@code size} is negative
486   */
487  public static ByteArrayDataOutput newDataOutput(int size) {
488    // When called at high frequency, boxing size generates too much garbage,
489    // so avoid doing that if we can.
490    if (size < 0) {
491      throw new IllegalArgumentException(String.format("Invalid size: %s", size));
492    }
493    return newDataOutput(new ByteArrayOutputStream(size));
494  }
495
496  /**
497   * Returns a new {@link ByteArrayDataOutput} instance which writes to the given {@code
498   * ByteArrayOutputStream}. The given output stream is not reset before being written to by the
499   * returned {@code ByteArrayDataOutput} and new data will be appended to any existing content.
500   *
501   * <p>Note that if the given output stream was not empty or is modified after the {@code
502   * ByteArrayDataOutput} is created, the contract for {@link ByteArrayDataOutput#toByteArray} will
503   * not be honored (the bytes returned in the byte array may not be exactly what was written via
504   * calls to {@code ByteArrayDataOutput}).
505   *
506   * @since 17.0
507   */
508  public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) {
509    return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream));
510  }
511
512  private static class ByteArrayDataOutputStream implements ByteArrayDataOutput {
513
514    final DataOutput output;
515    final ByteArrayOutputStream byteArrayOutputStream;
516
517    ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputStream) {
518      this.byteArrayOutputStream = byteArrayOutputStream;
519      output = new DataOutputStream(byteArrayOutputStream);
520    }
521
522    @Override
523    public void write(int b) {
524      try {
525        output.write(b);
526      } catch (IOException impossible) {
527        throw new AssertionError(impossible);
528      }
529    }
530
531    @Override
532    public void write(byte[] b) {
533      try {
534        output.write(b);
535      } catch (IOException impossible) {
536        throw new AssertionError(impossible);
537      }
538    }
539
540    @Override
541    public void write(byte[] b, int off, int len) {
542      try {
543        output.write(b, off, len);
544      } catch (IOException impossible) {
545        throw new AssertionError(impossible);
546      }
547    }
548
549    @Override
550    public void writeBoolean(boolean v) {
551      try {
552        output.writeBoolean(v);
553      } catch (IOException impossible) {
554        throw new AssertionError(impossible);
555      }
556    }
557
558    @Override
559    public void writeByte(int v) {
560      try {
561        output.writeByte(v);
562      } catch (IOException impossible) {
563        throw new AssertionError(impossible);
564      }
565    }
566
567    @Override
568    public void writeBytes(String s) {
569      try {
570        output.writeBytes(s);
571      } catch (IOException impossible) {
572        throw new AssertionError(impossible);
573      }
574    }
575
576    @Override
577    public void writeChar(int v) {
578      try {
579        output.writeChar(v);
580      } catch (IOException impossible) {
581        throw new AssertionError(impossible);
582      }
583    }
584
585    @Override
586    public void writeChars(String s) {
587      try {
588        output.writeChars(s);
589      } catch (IOException impossible) {
590        throw new AssertionError(impossible);
591      }
592    }
593
594    @Override
595    public void writeDouble(double v) {
596      try {
597        output.writeDouble(v);
598      } catch (IOException impossible) {
599        throw new AssertionError(impossible);
600      }
601    }
602
603    @Override
604    public void writeFloat(float v) {
605      try {
606        output.writeFloat(v);
607      } catch (IOException impossible) {
608        throw new AssertionError(impossible);
609      }
610    }
611
612    @Override
613    public void writeInt(int v) {
614      try {
615        output.writeInt(v);
616      } catch (IOException impossible) {
617        throw new AssertionError(impossible);
618      }
619    }
620
621    @Override
622    public void writeLong(long v) {
623      try {
624        output.writeLong(v);
625      } catch (IOException impossible) {
626        throw new AssertionError(impossible);
627      }
628    }
629
630    @Override
631    public void writeShort(int v) {
632      try {
633        output.writeShort(v);
634      } catch (IOException impossible) {
635        throw new AssertionError(impossible);
636      }
637    }
638
639    @Override
640    public void writeUTF(String s) {
641      try {
642        output.writeUTF(s);
643      } catch (IOException impossible) {
644        throw new AssertionError(impossible);
645      }
646    }
647
648    @Override
649    public byte[] toByteArray() {
650      return byteArrayOutputStream.toByteArray();
651    }
652  }
653
654  private static final OutputStream NULL_OUTPUT_STREAM =
655      new OutputStream() {
656        /** Discards the specified byte. */
657        @Override
658        public void write(int b) {}
659
660        /** Discards the specified byte array. */
661        @Override
662        public void write(byte[] b) {
663          checkNotNull(b);
664        }
665
666        /** Discards the specified byte array. */
667        @Override
668        public void write(byte[] b, int off, int len) {
669          checkNotNull(b);
670          checkPositionIndexes(off, off + len, b.length);
671        }
672
673        @Override
674        public String toString() {
675          return "ByteStreams.nullOutputStream()";
676        }
677      };
678
679  /**
680   * Returns an {@link OutputStream} that simply discards written bytes.
681   *
682   * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream)
683   */
684  public static OutputStream nullOutputStream() {
685    return NULL_OUTPUT_STREAM;
686  }
687
688  /**
689   * Wraps a {@link InputStream}, limiting the number of bytes which can be read.
690   *
691   * @param in the input stream to be wrapped
692   * @param limit the maximum number of bytes to be read
693   * @return a length-limited {@link InputStream}
694   * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream)
695   */
696  public static InputStream limit(InputStream in, long limit) {
697    return new LimitedInputStream(in, limit);
698  }
699
700  private static final class LimitedInputStream extends FilterInputStream {
701
702    private long left;
703    private long mark = -1;
704
705    LimitedInputStream(InputStream in, long limit) {
706      super(in);
707      checkNotNull(in);
708      checkArgument(limit >= 0, "limit must be non-negative");
709      left = limit;
710    }
711
712    @Override
713    public int available() throws IOException {
714      return (int) min(in.available(), left);
715    }
716
717    // it's okay to mark even if mark isn't supported, as reset won't work
718    @Override
719    public synchronized void mark(int readLimit) {
720      in.mark(readLimit);
721      mark = left;
722    }
723
724    @Override
725    public int read() throws IOException {
726      if (left == 0) {
727        return -1;
728      }
729
730      int result = in.read();
731      if (result != -1) {
732        --left;
733      }
734      return result;
735    }
736
737    @Override
738    public int read(byte[] b, int off, int len) throws IOException {
739      if (left == 0) {
740        return -1;
741      }
742
743      len = (int) min(len, left);
744      int result = in.read(b, off, len);
745      if (result != -1) {
746        left -= result;
747      }
748      return result;
749    }
750
751    @Override
752    public synchronized void reset() throws IOException {
753      if (!in.markSupported()) {
754        throw new IOException("Mark not supported");
755      }
756      if (mark == -1) {
757        throw new IOException("Mark not set");
758      }
759
760      in.reset();
761      left = mark;
762    }
763
764    @Override
765    public long skip(long n) throws IOException {
766      n = min(n, left);
767      long skipped = in.skip(n);
768      left -= skipped;
769      return skipped;
770    }
771  }
772
773  /**
774   * Attempts to read enough bytes from the stream to fill the given byte array, with the same
775   * behavior as {@link DataInput#readFully(byte[])}. Does not close the stream.
776   *
777   * @param in the input stream to read from.
778   * @param b the buffer into which the data is read.
779   * @throws EOFException if this stream reaches the end before reading all the bytes.
780   * @throws IOException if an I/O error occurs.
781   */
782  public static void readFully(InputStream in, byte[] b) throws IOException {
783    readFully(in, b, 0, b.length);
784  }
785
786  /**
787   * Attempts to read {@code len} bytes from the stream into the given array starting at {@code
788   * off}, with the same behavior as {@link DataInput#readFully(byte[], int, int)}. Does not close
789   * the stream.
790   *
791   * @param in the input stream to read from.
792   * @param b the buffer into which the data is read.
793   * @param off an int specifying the offset into the data.
794   * @param len an int specifying the number of bytes to read.
795   * @throws EOFException if this stream reaches the end before reading all the bytes.
796   * @throws IOException if an I/O error occurs.
797   */
798  public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException {
799    int read = read(in, b, off, len);
800    if (read != len) {
801      throw new EOFException(
802          "reached end of stream after reading " + read + " bytes; " + len + " bytes expected");
803    }
804  }
805
806  /**
807   * Discards {@code n} bytes of data from the input stream. This method will block until the full
808   * amount has been skipped. Does not close the stream.
809   *
810   * @param in the input stream to read from
811   * @param n the number of bytes to skip
812   * @throws EOFException if this stream reaches the end before skipping all the bytes
813   * @throws IOException if an I/O error occurs, or the stream does not support skipping
814   */
815  public static void skipFully(InputStream in, long n) throws IOException {
816    long skipped = skipUpTo(in, n);
817    if (skipped < n) {
818      throw new EOFException(
819          "reached end of stream after skipping " + skipped + " bytes; " + n + " bytes expected");
820    }
821  }
822
823  /**
824   * Discards up to {@code n} bytes of data from the input stream. This method will block until
825   * either the full amount has been skipped or until the end of the stream is reached, whichever
826   * happens first. Returns the total number of bytes skipped.
827   */
828  static long skipUpTo(InputStream in, long n) throws IOException {
829    long totalSkipped = 0;
830    // A buffer is allocated if skipSafely does not skip any bytes.
831    byte[] buf = null;
832
833    while (totalSkipped < n) {
834      long remaining = n - totalSkipped;
835      long skipped = skipSafely(in, remaining);
836
837      if (skipped == 0) {
838        // Do a buffered read since skipSafely could return 0 repeatedly, for example if
839        // in.available() always returns 0 (the default).
840        int skip = (int) min(remaining, BUFFER_SIZE);
841        if (buf == null) {
842          // Allocate a buffer bounded by the maximum size that can be requested, for
843          // example an array of BUFFER_SIZE is unnecessary when the value of remaining
844          // is smaller.
845          buf = new byte[skip];
846        }
847        if ((skipped = in.read(buf, 0, skip)) == -1) {
848          // Reached EOF
849          break;
850        }
851      }
852
853      totalSkipped += skipped;
854    }
855
856    return totalSkipped;
857  }
858
859  /**
860   * Attempts to skip up to {@code n} bytes from the given input stream, but not more than {@code
861   * in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes than
862   * actually remain in the file, something that it {@linkplain java.io.FileInputStream#skip(long)
863   * specifies} it can do in its Javadoc despite the fact that it is violating the contract of
864   * {@code InputStream.skip()}.
865   */
866  private static long skipSafely(InputStream in, long n) throws IOException {
867    int available = in.available();
868    return available == 0 ? 0 : in.skip(min(available, n));
869  }
870
871  /**
872   * Process the bytes of the given input stream using the given processor.
873   *
874   * @param input the input stream to process
875   * @param processor the object to which to pass the bytes of the stream
876   * @return the result of the byte processor
877   * @throws IOException if an I/O error occurs
878   * @since 14.0
879   */
880  @CanIgnoreReturnValue // some processors won't return a useful result
881  @ParametricNullness
882  public static <T extends @Nullable Object> T readBytes(
883      InputStream input, ByteProcessor<T> processor) throws IOException {
884    checkNotNull(input);
885    checkNotNull(processor);
886
887    byte[] buf = createBuffer();
888    int read;
889    do {
890      read = input.read(buf);
891    } while (read != -1 && processor.processBytes(buf, 0, read));
892    return processor.getResult();
893  }
894
895  /**
896   * Reads some bytes from an input stream and stores them into the buffer array {@code b}. This
897   * method blocks until {@code len} bytes of input data have been read into the array, or end of
898   * file is detected. The number of bytes read is returned, possibly zero. Does not close the
899   * stream.
900   *
901   * <p>A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent
902   * calls on the same stream will return zero.
903   *
904   * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative,
905   * or {@code len} is negative, or {@code off+len} is greater than the length of the array {@code
906   * b}, then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes
907   * are read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one
908   * into {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}.
909   *
910   * @param in the input stream to read from
911   * @param b the buffer into which the data is read
912   * @param off an int specifying the offset into the data
913   * @param len an int specifying the number of bytes to read
914   * @return the number of bytes read
915   * @throws IOException if an I/O error occurs
916   * @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if
917   *     {@code off + len} is greater than {@code b.length}
918   */
919  @CanIgnoreReturnValue
920  // Sometimes you don't care how many bytes you actually read, I guess.
921  // (You know that it's either going to read len bytes or stop at EOF.)
922  public static int read(InputStream in, byte[] b, int off, int len) throws IOException {
923    checkNotNull(in);
924    checkNotNull(b);
925    if (len < 0) {
926      throw new IndexOutOfBoundsException(String.format("len (%s) cannot be negative", len));
927    }
928    checkPositionIndexes(off, off + len, b.length);
929    int total = 0;
930    while (total < len) {
931      int result = in.read(b, off + total, len - total);
932      if (result == -1) {
933        break;
934      }
935      total += result;
936    }
937    return total;
938  }
939}