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