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