001/*
002 * Copyright (C) 2012 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.io.ByteStreams.createBuffer;
020import static com.google.common.io.ByteStreams.skipUpTo;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.Ascii;
025import com.google.common.base.Optional;
026import com.google.common.collect.ImmutableList;
027import com.google.common.hash.Funnels;
028import com.google.common.hash.HashCode;
029import com.google.common.hash.HashFunction;
030import com.google.common.hash.Hasher;
031import com.google.errorprone.annotations.CanIgnoreReturnValue;
032import java.io.BufferedInputStream;
033import java.io.ByteArrayInputStream;
034import java.io.IOException;
035import java.io.InputStream;
036import java.io.InputStreamReader;
037import java.io.OutputStream;
038import java.io.Reader;
039import java.nio.charset.Charset;
040import java.util.Arrays;
041import java.util.Iterator;
042
043/**
044 * A readable source of bytes, such as a file. Unlike an {@link InputStream}, a {@code ByteSource}
045 * is not an open, stateful stream for input that can be read and closed. Instead, it is an
046 * immutable <i>supplier</i> of {@code InputStream} instances.
047 *
048 * <p>{@code ByteSource} provides two kinds of methods:
049 * <ul>
050 * <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent
051 *     instance each time they are called. The caller is responsible for ensuring that the returned
052 *     stream is closed.
053 * <li><b>Convenience methods:</b> These are implementations of common operations that are typically
054 *     implemented by opening a stream using one of the methods in the first category, doing
055 *     something and finally closing the stream that was opened.
056 * </ul>
057 *
058 * @since 14.0
059 * @author Colin Decker
060 */
061@GwtIncompatible
062public abstract class ByteSource {
063
064  /**
065   * Constructor for use by subclasses.
066   */
067  protected ByteSource() {}
068
069  /**
070   * Returns a {@link CharSource} view of this byte source that decodes bytes read from this source
071   * as characters using the given {@link Charset}.
072   *
073   * <p>If {@link CharSource#asByteSource} is called on the returned source with the same charset,
074   * the default implementation of this method will ensure that the original {@code ByteSource} is
075   * returned, rather than round-trip encoding. Subclasses that override this method should behave
076   * the same way.
077   */
078  public CharSource asCharSource(Charset charset) {
079    return new AsCharSource(charset);
080  }
081
082  /**
083   * Opens a new {@link InputStream} for reading from this source. This method should return a new,
084   * independent stream each time it is called.
085   *
086   * <p>The caller is responsible for ensuring that the returned stream is closed.
087   *
088   * @throws IOException if an I/O error occurs in the process of opening the stream
089   */
090  public abstract InputStream openStream() throws IOException;
091
092  /**
093   * Opens a new buffered {@link InputStream} for reading from this source. The returned stream is
094   * not required to be a {@link BufferedInputStream} in order to allow implementations to simply
095   * delegate to {@link #openStream()} when the stream returned by that method does not benefit from
096   * additional buffering (for example, a {@code ByteArrayInputStream}). This method should return a
097   * new, independent stream each time it is called.
098   *
099   * <p>The caller is responsible for ensuring that the returned stream is closed.
100   *
101   * @throws IOException if an I/O error occurs in the process of opening the stream
102   * @since 15.0 (in 14.0 with return type {@link BufferedInputStream})
103   */
104  public InputStream openBufferedStream() throws IOException {
105    InputStream in = openStream();
106    return (in instanceof BufferedInputStream)
107        ? (BufferedInputStream) in
108        : new BufferedInputStream(in);
109  }
110
111  /**
112   * Returns a view of a slice of this byte source that is at most {@code length} bytes long
113   * starting at the given {@code offset}. If {@code offset} is greater than the size of this
114   * source, the returned source will be empty. If {@code offset + length} is greater than the size
115   * of this source, the returned source will contain the slice starting at {@code offset} and
116   * ending at the end of this source.
117   *
118   * @throws IllegalArgumentException if {@code offset} or {@code length} is negative
119   */
120  public ByteSource slice(long offset, long length) {
121    return new SlicedByteSource(offset, length);
122  }
123
124  /**
125   * Returns whether the source has zero bytes. The default implementation returns true if
126   * {@link #sizeIfKnown} returns zero, falling back to opening a stream and checking for EOF if the
127   * size is not known.
128   *
129   * <p>Note that, in cases where {@code sizeIfKnown} returns zero, it is <i>possible</i> that bytes
130   * are actually available for reading. (For example, some special files may return a size of 0
131   * despite actually having content when read.) This means that a source may return {@code true}
132   * from {@code isEmpty()} despite having readable content.
133   *
134   * @throws IOException if an I/O error occurs
135   * @since 15.0
136   */
137  public boolean isEmpty() throws IOException {
138    Optional<Long> sizeIfKnown = sizeIfKnown();
139    if (sizeIfKnown.isPresent() && sizeIfKnown.get() == 0L) {
140      return true;
141    }
142    Closer closer = Closer.create();
143    try {
144      InputStream in = closer.register(openStream());
145      return in.read() == -1;
146    } catch (Throwable e) {
147      throw closer.rethrow(e);
148    } finally {
149      closer.close();
150    }
151  }
152
153  /**
154   * Returns the size of this source in bytes, if the size can be easily determined without actually
155   * opening the data stream.
156   *
157   * <p>The default implementation returns {@link Optional#absent}. Some sources, such as a file,
158   * may return a non-absent value. Note that in such cases, it is <i>possible</i> that this method
159   * will return a different number of bytes than would be returned by reading all of the bytes (for
160   * example, some special files may return a size of 0 despite actually having content when read).
161   *
162   * <p>Additionally, for mutable sources such as files, a subsequent read may return a different
163   * number of bytes if the contents are changed.
164   *
165   * @since 19.0
166   */
167  @Beta
168  public Optional<Long> sizeIfKnown() {
169    return Optional.absent();
170  }
171
172  /**
173   * Returns the size of this source in bytes, even if doing so requires opening and traversing an
174   * entire stream. To avoid a potentially expensive operation, see {@link #sizeIfKnown}.
175   *
176   * <p>The default implementation calls {@link #sizeIfKnown} and returns the value if present. If
177   * absent, it will fall back to a heavyweight operation that will open a stream, read (or
178   * {@link InputStream#skip(long) skip}, if possible) to the end of the stream and return the total
179   * number of bytes that were read.
180   *
181   * <p>Note that for some sources that implement {@link #sizeIfKnown} to provide a more efficient
182   * implementation, it is <i>possible</i> that this method will return a different number of bytes
183   * than would be returned by reading all of the bytes (for example, some special files may return
184   * a size of 0 despite actually having content when read).
185   *
186   * <p>In either case, for mutable sources such as files, a subsequent read may return a different
187   * number of bytes if the contents are changed.
188   *
189   * @throws IOException if an I/O error occurs in the process of reading the size of this source
190   */
191  public long size() throws IOException {
192    Optional<Long> sizeIfKnown = sizeIfKnown();
193    if (sizeIfKnown.isPresent()) {
194      return sizeIfKnown.get();
195    }
196
197    Closer closer = Closer.create();
198    try {
199      InputStream in = closer.register(openStream());
200      return countBySkipping(in);
201    } catch (IOException e) {
202      // skip may not be supported... at any rate, try reading
203    } finally {
204      closer.close();
205    }
206
207    closer = Closer.create();
208    try {
209      InputStream in = closer.register(openStream());
210      return ByteStreams.exhaust(in);
211    } catch (Throwable e) {
212      throw closer.rethrow(e);
213    } finally {
214      closer.close();
215    }
216  }
217
218  /**
219   * Counts the bytes in the given input stream using skip if possible. Returns SKIP_FAILED if the
220   * first call to skip threw, in which case skip may just not be supported.
221   */
222  private long countBySkipping(InputStream in) throws IOException {
223    long count = 0;
224    long skipped;
225    while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) {
226      count += skipped;
227    }
228    return count;
229  }
230
231  /**
232   * Copies the contents of this byte source to the given {@code OutputStream}. Does not close
233   * {@code output}.
234   *
235   * @return the number of bytes copied
236   * @throws IOException if an I/O error occurs in the process of reading from this source or
237   *     writing to {@code output}
238   */
239  @CanIgnoreReturnValue
240  public long copyTo(OutputStream output) throws IOException {
241    checkNotNull(output);
242
243    Closer closer = Closer.create();
244    try {
245      InputStream in = closer.register(openStream());
246      return ByteStreams.copy(in, output);
247    } catch (Throwable e) {
248      throw closer.rethrow(e);
249    } finally {
250      closer.close();
251    }
252  }
253
254  /**
255   * Copies the contents of this byte source to the given {@code ByteSink}.
256   *
257   * @return the number of bytes copied
258   * @throws IOException if an I/O error occurs in the process of reading from this source or
259   *     writing to {@code sink}
260   */
261  @CanIgnoreReturnValue
262  public long copyTo(ByteSink sink) throws IOException {
263    checkNotNull(sink);
264
265    Closer closer = Closer.create();
266    try {
267      InputStream in = closer.register(openStream());
268      OutputStream out = closer.register(sink.openStream());
269      return ByteStreams.copy(in, out);
270    } catch (Throwable e) {
271      throw closer.rethrow(e);
272    } finally {
273      closer.close();
274    }
275  }
276
277  /**
278   * Reads the full contents of this byte source as a byte array.
279   *
280   * @throws IOException if an I/O error occurs in the process of reading from this source
281   */
282  public byte[] read() throws IOException {
283    Closer closer = Closer.create();
284    try {
285      InputStream in = closer.register(openStream());
286      return ByteStreams.toByteArray(in);
287    } catch (Throwable e) {
288      throw closer.rethrow(e);
289    } finally {
290      closer.close();
291    }
292  }
293
294  /**
295   * Reads the contents of this byte source using the given {@code processor} to process bytes as
296   * they are read. Stops when all bytes have been read or the consumer returns {@code false}.
297   * Returns the result produced by the processor.
298   *
299   * @throws IOException if an I/O error occurs in the process of reading from this source or if
300   *     {@code processor} throws an {@code IOException}
301   * @since 16.0
302   */
303  @Beta
304  @CanIgnoreReturnValue // some processors won't return a useful result
305  public <T> T read(ByteProcessor<T> processor) throws IOException {
306    checkNotNull(processor);
307
308    Closer closer = Closer.create();
309    try {
310      InputStream in = closer.register(openStream());
311      return ByteStreams.readBytes(in, processor);
312    } catch (Throwable e) {
313      throw closer.rethrow(e);
314    } finally {
315      closer.close();
316    }
317  }
318
319  /**
320   * Hashes the contents of this byte source using the given hash function.
321   *
322   * @throws IOException if an I/O error occurs in the process of reading from this source
323   */
324  public HashCode hash(HashFunction hashFunction) throws IOException {
325    Hasher hasher = hashFunction.newHasher();
326    copyTo(Funnels.asOutputStream(hasher));
327    return hasher.hash();
328  }
329
330  /**
331   * Checks that the contents of this byte source are equal to the contents of the given byte
332   * source.
333   *
334   * @throws IOException if an I/O error occurs in the process of reading from this source or
335   *     {@code other}
336   */
337  public boolean contentEquals(ByteSource other) throws IOException {
338    checkNotNull(other);
339
340    byte[] buf1 = createBuffer();
341    byte[] buf2 = createBuffer();
342
343    Closer closer = Closer.create();
344    try {
345      InputStream in1 = closer.register(openStream());
346      InputStream in2 = closer.register(other.openStream());
347      while (true) {
348        int read1 = ByteStreams.read(in1, buf1, 0, buf1.length);
349        int read2 = ByteStreams.read(in2, buf2, 0, buf2.length);
350        if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
351          return false;
352        } else if (read1 != buf1.length) {
353          return true;
354        }
355      }
356    } catch (Throwable e) {
357      throw closer.rethrow(e);
358    } finally {
359      closer.close();
360    }
361  }
362
363  /**
364   * Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
365   * the source will contain the concatenated data from the streams of the underlying sources.
366   *
367   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
368   * close the open underlying stream.
369   *
370   * @param sources the sources to concatenate
371   * @return a {@code ByteSource} containing the concatenated data
372   * @since 15.0
373   */
374  public static ByteSource concat(Iterable<? extends ByteSource> sources) {
375    return new ConcatenatedByteSource(sources);
376  }
377
378  /**
379   * Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
380   * the source will contain the concatenated data from the streams of the underlying sources.
381   *
382   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
383   * close the open underlying stream.
384   *
385   * <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method
386   * is called. This will fail if the iterator is infinite and may cause problems if the iterator
387   * eagerly fetches data for each source when iterated (rather than producing sources that only
388   * load data through their streams). Prefer using the {@link #concat(Iterable)} overload if
389   * possible.
390   *
391   * @param sources the sources to concatenate
392   * @return a {@code ByteSource} containing the concatenated data
393   * @throws NullPointerException if any of {@code sources} is {@code null}
394   * @since 15.0
395   */
396  public static ByteSource concat(Iterator<? extends ByteSource> sources) {
397    return concat(ImmutableList.copyOf(sources));
398  }
399
400  /**
401   * Concatenates multiple {@link ByteSource} instances into a single source. Streams returned from
402   * the source will contain the concatenated data from the streams of the underlying sources.
403   *
404   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
405   * close the open underlying stream.
406   *
407   * @param sources the sources to concatenate
408   * @return a {@code ByteSource} containing the concatenated data
409   * @throws NullPointerException if any of {@code sources} is {@code null}
410   * @since 15.0
411   */
412  public static ByteSource concat(ByteSource... sources) {
413    return concat(ImmutableList.copyOf(sources));
414  }
415
416  /**
417   * Returns a view of the given byte array as a {@link ByteSource}. To view only a specific range
418   * in the array, use {@code ByteSource.wrap(b).slice(offset, length)}.
419   *
420   * @since 15.0 (since 14.0 as {@code ByteStreams.asByteSource(byte[])}).
421   */
422  public static ByteSource wrap(byte[] b) {
423    return new ByteArrayByteSource(b);
424  }
425
426  /**
427   * Returns an immutable {@link ByteSource} that contains no bytes.
428   *
429   * @since 15.0
430   */
431  public static ByteSource empty() {
432    return EmptyByteSource.INSTANCE;
433  }
434
435  /**
436   * A char source that reads bytes from this source and decodes them as characters using a charset.
437   */
438  private final class AsCharSource extends CharSource {
439
440    final Charset charset;
441
442    AsCharSource(Charset charset) {
443      this.charset = checkNotNull(charset);
444    }
445
446    @Override
447    public ByteSource asByteSource(Charset charset) {
448      if (charset.equals(this.charset)) {
449        return ByteSource.this;
450      }
451      return super.asByteSource(charset);
452    }
453
454    @Override
455    public Reader openStream() throws IOException {
456      return new InputStreamReader(ByteSource.this.openStream(), charset);
457    }
458
459    @Override
460    public String toString() {
461      return ByteSource.this.toString() + ".asCharSource(" + charset + ")";
462    }
463  }
464
465  /**
466   * A view of a subsection of the containing byte source.
467   */
468  private final class SlicedByteSource extends ByteSource {
469
470    final long offset;
471    final long length;
472
473    SlicedByteSource(long offset, long length) {
474      checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
475      checkArgument(length >= 0, "length (%s) may not be negative", length);
476      this.offset = offset;
477      this.length = length;
478    }
479
480    @Override
481    public InputStream openStream() throws IOException {
482      return sliceStream(ByteSource.this.openStream());
483    }
484
485    @Override
486    public InputStream openBufferedStream() throws IOException {
487      return sliceStream(ByteSource.this.openBufferedStream());
488    }
489
490    private InputStream sliceStream(InputStream in) throws IOException {
491      if (offset > 0) {
492        long skipped;
493        try {
494          skipped = ByteStreams.skipUpTo(in, offset);
495        } catch (Throwable e) {
496          Closer closer = Closer.create();
497          closer.register(in);
498          try {
499            throw closer.rethrow(e);
500          } finally {
501            closer.close();
502          }
503        }
504
505        if (skipped < offset) {
506          // offset was beyond EOF
507          in.close();
508          return new ByteArrayInputStream(new byte[0]);
509        }
510      }
511      return ByteStreams.limit(in, length);
512    }
513
514    @Override
515    public ByteSource slice(long offset, long length) {
516      checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
517      checkArgument(length >= 0, "length (%s) may not be negative", length);
518      long maxLength = this.length - offset;
519      return ByteSource.this.slice(this.offset + offset, Math.min(length, maxLength));
520    }
521
522    @Override
523    public boolean isEmpty() throws IOException {
524      return length == 0 || super.isEmpty();
525    }
526
527    @Override
528    public Optional<Long> sizeIfKnown() {
529      Optional<Long> optionalUnslicedSize = ByteSource.this.sizeIfKnown();
530      if (optionalUnslicedSize.isPresent()) {
531        long unslicedSize = optionalUnslicedSize.get();
532        long off = Math.min(offset, unslicedSize);
533        return Optional.of(Math.min(length, unslicedSize - off));
534      }
535      return Optional.absent();
536    }
537
538    @Override
539    public String toString() {
540      return ByteSource.this.toString() + ".slice(" + offset + ", " + length + ")";
541    }
542  }
543
544  private static class ByteArrayByteSource extends ByteSource {
545
546    final byte[] bytes;
547    final int offset;
548    final int length;
549
550    ByteArrayByteSource(byte[] bytes) {
551      this(bytes, 0, bytes.length);
552    }
553
554    // NOTE: Preconditions are enforced by slice, the only non-trivial caller.
555    ByteArrayByteSource(byte[] bytes, int offset, int length) {
556      this.bytes = bytes;
557      this.offset = offset;
558      this.length = length;
559    }
560
561    @Override
562    public InputStream openStream() {
563      return new ByteArrayInputStream(bytes, offset, length);
564    }
565
566    @Override
567    public InputStream openBufferedStream() throws IOException {
568      return openStream();
569    }
570
571    @Override
572    public boolean isEmpty() {
573      return length == 0;
574    }
575
576    @Override
577    public long size() {
578      return length;
579    }
580
581    @Override
582    public Optional<Long> sizeIfKnown() {
583      return Optional.of((long) length);
584    }
585
586    @Override
587    public byte[] read() {
588      return Arrays.copyOfRange(bytes, offset, offset + length);
589    }
590
591    @Override
592    public long copyTo(OutputStream output) throws IOException {
593      output.write(bytes, offset, length);
594      return length;
595    }
596
597    @SuppressWarnings("CheckReturnValue") // it doesn't matter what processBytes returns here
598    @Override
599    public <T> T read(ByteProcessor<T> processor) throws IOException {
600      processor.processBytes(bytes, offset, length);
601      return processor.getResult();
602    }
603
604    @Override
605    public HashCode hash(HashFunction hashFunction) throws IOException {
606      return hashFunction.hashBytes(bytes, offset, length);
607    }
608
609    @Override
610    public ByteSource slice(long offset, long length) {
611      checkArgument(offset >= 0, "offset (%s) may not be negative", offset);
612      checkArgument(length >= 0, "length (%s) may not be negative", length);
613
614      offset = Math.min(offset, this.length);
615      length = Math.min(length, this.length - offset);
616      int newOffset = this.offset + (int) offset;
617      return new ByteArrayByteSource(bytes, newOffset, (int) length);
618    }
619
620    @Override
621    public String toString() {
622      return "ByteSource.wrap("
623          + Ascii.truncate(BaseEncoding.base16().encode(bytes, offset, length), 30, "...") + ")";
624    }
625  }
626
627  private static final class EmptyByteSource extends ByteArrayByteSource {
628
629    static final EmptyByteSource INSTANCE = new EmptyByteSource();
630
631    EmptyByteSource() {
632      super(new byte[0]);
633    }
634
635    @Override
636    public CharSource asCharSource(Charset charset) {
637      checkNotNull(charset);
638      return CharSource.empty();
639    }
640
641    @Override
642    public byte[] read() {
643      return bytes; // length is 0, no need to clone
644    }
645
646    @Override
647    public String toString() {
648      return "ByteSource.empty()";
649    }
650  }
651
652  private static final class ConcatenatedByteSource extends ByteSource {
653
654    final Iterable<? extends ByteSource> sources;
655
656    ConcatenatedByteSource(Iterable<? extends ByteSource> sources) {
657      this.sources = checkNotNull(sources);
658    }
659
660    @Override
661    public InputStream openStream() throws IOException {
662      return new MultiInputStream(sources.iterator());
663    }
664
665    @Override
666    public boolean isEmpty() throws IOException {
667      for (ByteSource source : sources) {
668        if (!source.isEmpty()) {
669          return false;
670        }
671      }
672      return true;
673    }
674
675    @Override
676    public Optional<Long> sizeIfKnown() {
677      long result = 0L;
678      for (ByteSource source : sources) {
679        Optional<Long> sizeIfKnown = source.sizeIfKnown();
680        if (!sizeIfKnown.isPresent()) {
681          return Optional.absent();
682        }
683        result += sizeIfKnown.get();
684      }
685      return Optional.of(result);
686    }
687
688    @Override
689    public long size() throws IOException {
690      long result = 0L;
691      for (ByteSource source : sources) {
692        result += source.size();
693      }
694      return result;
695    }
696
697    @Override
698    public String toString() {
699      return "ByteSource.concat(" + sources + ")";
700    }
701  }
702}