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.checkNotNull;
018import static com.google.common.collect.Streams.stream;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.common.base.Ascii;
023import com.google.common.base.Optional;
024import com.google.common.base.Splitter;
025import com.google.common.collect.AbstractIterator;
026import com.google.common.collect.ImmutableList;
027import com.google.common.collect.Lists;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import com.google.errorprone.annotations.MustBeClosed;
030import java.io.BufferedReader;
031import java.io.Closeable;
032import java.io.IOException;
033import java.io.InputStream;
034import java.io.Reader;
035import java.io.StringReader;
036import java.io.UncheckedIOException;
037import java.io.Writer;
038import java.nio.charset.Charset;
039import java.util.Iterator;
040import java.util.List;
041import java.util.function.Consumer;
042import java.util.stream.Stream;
043import javax.annotation.CheckForNull;
044import org.checkerframework.checker.nullness.qual.Nullable;
045
046/**
047 * A readable source of characters, such as a text file. Unlike a {@link Reader}, a {@code
048 * CharSource} is not an open, stateful stream of characters that can be read and closed. Instead,
049 * it is an immutable <i>supplier</i> of {@code Reader} instances.
050 *
051 * <p>{@code CharSource} provides two kinds of methods:
052 *
053 * <ul>
054 *   <li><b>Methods that return a reader:</b> These methods should return a <i>new</i>, independent
055 *       instance each time they are called. The caller is responsible for ensuring that the
056 *       returned reader is closed.
057 *   <li><b>Convenience methods:</b> These are implementations of common operations that are
058 *       typically implemented by opening a reader using one of the methods in the first category,
059 *       doing something and finally closing the reader that was opened.
060 * </ul>
061 *
062 * <p>Several methods in this class, such as {@link #readLines()}, break the contents of the source
063 * into lines. Like {@link BufferedReader}, these methods break lines on any of {@code \n}, {@code
064 * \r} or {@code \r\n}, do not include the line separator in each line and do not consider there to
065 * be an empty line at the end if the contents are terminated with a line separator.
066 *
067 * <p>Any {@link ByteSource} containing text encoded with a specific {@linkplain Charset character
068 * encoding} may be viewed as a {@code CharSource} using {@link ByteSource#asCharSource(Charset)}.
069 *
070 * <p><b>Note:</b> In general, {@code CharSource} is intended to be used for "file-like" sources
071 * that provide readers that are:
072 *
073 * <ul>
074 *   <li><b>Finite:</b> Many operations, such as {@link #length()} and {@link #read()}, will either
075 *       block indefinitely or fail if the source creates an infinite reader.
076 *   <li><b>Non-destructive:</b> A <i>destructive</i> reader will consume or otherwise alter the
077 *       source as they are read from it. A source that provides such readers will not be reusable,
078 *       and operations that read from the stream (including {@link #length()}, in some
079 *       implementations) will prevent further operations from completing as expected.
080 * </ul>
081 *
082 * @since 14.0
083 * @author Colin Decker
084 */
085@J2ktIncompatible
086@GwtIncompatible
087@ElementTypesAreNonnullByDefault
088public abstract class CharSource {
089
090  /** Constructor for use by subclasses. */
091  protected CharSource() {}
092
093  /**
094   * Returns a {@link ByteSource} view of this char source that encodes chars read from this source
095   * as bytes using the given {@link Charset}.
096   *
097   * <p>If {@link ByteSource#asCharSource} is called on the returned source with the same charset,
098   * the default implementation of this method will ensure that the original {@code CharSource} is
099   * returned, rather than round-trip encoding. Subclasses that override this method should behave
100   * the same way.
101   *
102   * @since 20.0
103   */
104  public ByteSource asByteSource(Charset charset) {
105    return new AsByteSource(charset);
106  }
107
108  /**
109   * Opens a new {@link Reader} for reading from this source. This method returns a new, independent
110   * reader each time it is called.
111   *
112   * <p>The caller is responsible for ensuring that the returned reader is closed.
113   *
114   * @throws IOException if an I/O error occurs while opening the reader
115   */
116  public abstract Reader openStream() throws IOException;
117
118  /**
119   * Opens a new {@link BufferedReader} for reading from this source. This method returns a new,
120   * independent reader each time it is called.
121   *
122   * <p>The caller is responsible for ensuring that the returned reader is closed.
123   *
124   * @throws IOException if an I/O error occurs while of opening the reader
125   */
126  public BufferedReader openBufferedStream() throws IOException {
127    Reader reader = openStream();
128    return (reader instanceof BufferedReader)
129        ? (BufferedReader) reader
130        : new BufferedReader(reader);
131  }
132
133  /**
134   * Opens a new {@link Stream} for reading text one line at a time from this source. This method
135   * returns a new, independent stream each time it is called.
136   *
137   * <p>The returned stream is lazy and only reads from the source in the terminal operation. If an
138   * I/O error occurs while the stream is reading from the source or when the stream is closed, an
139   * {@link UncheckedIOException} is thrown.
140   *
141   * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
142   * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
143   * \n}. If the source's content does not end in a line termination sequence, it is treated as if
144   * it does.
145   *
146   * <p>The caller is responsible for ensuring that the returned stream is closed. For example:
147   *
148   * <pre>{@code
149   * try (Stream<String> lines = source.lines()) {
150   *   lines.map(...)
151   *      .filter(...)
152   *      .forEach(...);
153   * }
154   * }</pre>
155   *
156   * @throws IOException if an I/O error occurs while opening the stream
157   * @since 33.4.0 (but since 22.0 in the JRE flavor)
158   */
159  @MustBeClosed
160  @SuppressWarnings("Java7ApiChecker")
161  // If users use this when they shouldn't, we hope that NewApi will catch subsequent Stream calls.
162  @IgnoreJRERequirement
163  public Stream<String> lines() throws IOException {
164    BufferedReader reader = openBufferedStream();
165    return reader.lines().onClose(() -> closeUnchecked(reader));
166  }
167
168  @SuppressWarnings("Java7ApiChecker")
169  @IgnoreJRERequirement // helper for lines()
170  /*
171   * If we make these calls inline inside the lambda inside lines(), we get an Animal Sniffer error,
172   * despite the @IgnoreJRERequirement annotation there. For details, see ImmutableSortedMultiset.
173   */
174  private static void closeUnchecked(Closeable closeable) {
175    try {
176      closeable.close();
177    } catch (IOException e) {
178      throw new UncheckedIOException(e);
179    }
180  }
181
182  /**
183   * Returns the size of this source in chars, if the size can be easily determined without actually
184   * opening the data stream.
185   *
186   * <p>The default implementation returns {@link Optional#absent}. Some sources, such as a {@code
187   * CharSequence}, may return a non-absent value. Note that in such cases, it is <i>possible</i>
188   * that this method will return a different number of chars than would be returned by reading all
189   * of the chars.
190   *
191   * <p>Additionally, for mutable sources such as {@code StringBuilder}s, a subsequent read may
192   * return a different number of chars if the contents are changed.
193   *
194   * @since 19.0
195   */
196  public Optional<Long> lengthIfKnown() {
197    return Optional.absent();
198  }
199
200  /**
201   * Returns the length of this source in chars, even if doing so requires opening and traversing an
202   * entire stream. To avoid a potentially expensive operation, see {@link #lengthIfKnown}.
203   *
204   * <p>The default implementation calls {@link #lengthIfKnown} and returns the value if present. If
205   * absent, it will fall back to a heavyweight operation that will open a stream, {@link
206   * Reader#skip(long) skip} to the end of the stream, and return the total number of chars that
207   * were skipped.
208   *
209   * <p>Note that for sources that implement {@link #lengthIfKnown} to provide a more efficient
210   * implementation, it is <i>possible</i> that this method will return a different number of chars
211   * than would be returned by reading all of the chars.
212   *
213   * <p>In either case, for mutable sources such as files, a subsequent read may return a different
214   * number of chars if the contents are changed.
215   *
216   * @throws IOException if an I/O error occurs while reading the length of this source
217   * @since 19.0
218   */
219  public long length() throws IOException {
220    Optional<Long> lengthIfKnown = lengthIfKnown();
221    if (lengthIfKnown.isPresent()) {
222      return lengthIfKnown.get();
223    }
224
225    Closer closer = Closer.create();
226    try {
227      Reader reader = closer.register(openStream());
228      return countBySkipping(reader);
229    } catch (Throwable e) {
230      throw closer.rethrow(e);
231    } finally {
232      closer.close();
233    }
234  }
235
236  private long countBySkipping(Reader reader) throws IOException {
237    long count = 0;
238    long read;
239    while ((read = reader.skip(Long.MAX_VALUE)) != 0) {
240      count += read;
241    }
242    return count;
243  }
244
245  /**
246   * Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}).
247   * Does not close {@code appendable} if it is {@code Closeable}.
248   *
249   * @return the number of characters copied
250   * @throws IOException if an I/O error occurs while reading from this source or writing to {@code
251   *     appendable}
252   */
253  @CanIgnoreReturnValue
254  public long copyTo(Appendable appendable) throws IOException {
255    checkNotNull(appendable);
256
257    Closer closer = Closer.create();
258    try {
259      Reader reader = closer.register(openStream());
260      return CharStreams.copy(reader, appendable);
261    } catch (Throwable e) {
262      throw closer.rethrow(e);
263    } finally {
264      closer.close();
265    }
266  }
267
268  /**
269   * Copies the contents of this source to the given sink.
270   *
271   * @return the number of characters copied
272   * @throws IOException if an I/O error occurs while reading from this source or writing to {@code
273   *     sink}
274   */
275  @CanIgnoreReturnValue
276  public long copyTo(CharSink sink) throws IOException {
277    checkNotNull(sink);
278
279    Closer closer = Closer.create();
280    try {
281      Reader reader = closer.register(openStream());
282      Writer writer = closer.register(sink.openStream());
283      return CharStreams.copy(reader, writer);
284    } catch (Throwable e) {
285      throw closer.rethrow(e);
286    } finally {
287      closer.close();
288    }
289  }
290
291  /**
292   * Reads the contents of this source as a string.
293   *
294   * @throws IOException if an I/O error occurs while reading from this source
295   */
296  public String read() throws IOException {
297    Closer closer = Closer.create();
298    try {
299      Reader reader = closer.register(openStream());
300      return CharStreams.toString(reader);
301    } catch (Throwable e) {
302      throw closer.rethrow(e);
303    } finally {
304      closer.close();
305    }
306  }
307
308  /**
309   * Reads the first line of this source as a string. Returns {@code null} if this source is empty.
310   *
311   * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
312   * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
313   * \n}. If the source's content does not end in a line termination sequence, it is treated as if
314   * it does.
315   *
316   * @throws IOException if an I/O error occurs while reading from this source
317   */
318  @CheckForNull
319  public String readFirstLine() throws IOException {
320    Closer closer = Closer.create();
321    try {
322      BufferedReader reader = closer.register(openBufferedStream());
323      return reader.readLine();
324    } catch (Throwable e) {
325      throw closer.rethrow(e);
326    } finally {
327      closer.close();
328    }
329  }
330
331  /**
332   * Reads all the lines of this source as a list of strings. The returned list will be empty if
333   * this source is empty.
334   *
335   * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
336   * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
337   * \n}. If the source's content does not end in a line termination sequence, it is treated as if
338   * it does.
339   *
340   * @throws IOException if an I/O error occurs while reading from this source
341   */
342  public ImmutableList<String> readLines() throws IOException {
343    Closer closer = Closer.create();
344    try {
345      BufferedReader reader = closer.register(openBufferedStream());
346      List<String> result = Lists.newArrayList();
347      String line;
348      while ((line = reader.readLine()) != null) {
349        result.add(line);
350      }
351      return ImmutableList.copyOf(result);
352    } catch (Throwable e) {
353      throw closer.rethrow(e);
354    } finally {
355      closer.close();
356    }
357  }
358
359  /**
360   * Reads lines of text from this source, processing each line as it is read using the given {@link
361   * LineProcessor processor}. Stops when all lines have been processed or the processor returns
362   * {@code false} and returns the result produced by the processor.
363   *
364   * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
365   * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
366   * \n}. If the source's content does not end in a line termination sequence, it is treated as if
367   * it does.
368   *
369   * @throws IOException if an I/O error occurs while reading from this source or if {@code
370   *     processor} throws an {@code IOException}
371   * @since 16.0
372   */
373  @CanIgnoreReturnValue // some processors won't return a useful result
374  @ParametricNullness
375  public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException {
376    checkNotNull(processor);
377
378    Closer closer = Closer.create();
379    try {
380      Reader reader = closer.register(openStream());
381      return CharStreams.readLines(reader, processor);
382    } catch (Throwable e) {
383      throw closer.rethrow(e);
384    } finally {
385      closer.close();
386    }
387  }
388
389  /**
390   * Reads all lines of text from this source, running the given {@code action} for each line as it
391   * is read.
392   *
393   * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of
394   * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code
395   * \n}. If the source's content does not end in a line termination sequence, it is treated as if
396   * it does.
397   *
398   * @throws IOException if an I/O error occurs while reading from this source or if {@code action}
399   *     throws an {@code UncheckedIOException}
400   * @since 33.4.0 (but since 22.0 in the JRE flavor)
401   */
402  @SuppressWarnings("Java7ApiChecker")
403  /*
404   * We have to rely on users not to call this without library desugaring, as NewApi won't flag
405   * Consumer creation.
406   */
407  @IgnoreJRERequirement
408  public void forEachLine(Consumer<? super String> action) throws IOException {
409    try (Stream<String> lines = lines()) {
410      // The lines should be ordered regardless in most cases, but use forEachOrdered to be sure
411      lines.forEachOrdered(action);
412    } catch (UncheckedIOException e) {
413      throw e.getCause();
414    }
415  }
416
417  /**
418   * Returns whether the source has zero chars. The default implementation first checks {@link
419   * #lengthIfKnown}, returning true if it's known to be zero and false if it's known to be
420   * non-zero. If the length is not known, it falls back to opening a stream and checking for EOF.
421   *
422   * <p>Note that, in cases where {@code lengthIfKnown} returns zero, it is <i>possible</i> that
423   * chars are actually available for reading. This means that a source may return {@code true} from
424   * {@code isEmpty()} despite having readable content.
425   *
426   * @throws IOException if an I/O error occurs
427   * @since 15.0
428   */
429  public boolean isEmpty() throws IOException {
430    Optional<Long> lengthIfKnown = lengthIfKnown();
431    if (lengthIfKnown.isPresent()) {
432      return lengthIfKnown.get() == 0L;
433    }
434    Closer closer = Closer.create();
435    try {
436      Reader reader = closer.register(openStream());
437      return reader.read() == -1;
438    } catch (Throwable e) {
439      throw closer.rethrow(e);
440    } finally {
441      closer.close();
442    }
443  }
444
445  /**
446   * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from
447   * the source will contain the concatenated data from the streams of the underlying sources.
448   *
449   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
450   * close the open underlying stream.
451   *
452   * @param sources the sources to concatenate
453   * @return a {@code CharSource} containing the concatenated data
454   * @since 15.0
455   */
456  public static CharSource concat(Iterable<? extends CharSource> sources) {
457    return new ConcatenatedCharSource(sources);
458  }
459
460  /**
461   * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from
462   * the source will contain the concatenated data from the streams of the underlying sources.
463   *
464   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
465   * close the open underlying stream.
466   *
467   * <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method
468   * is called. This will fail if the iterator is infinite and may cause problems if the iterator
469   * eagerly fetches data for each source when iterated (rather than producing sources that only
470   * load data through their streams). Prefer using the {@link #concat(Iterable)} overload if
471   * possible.
472   *
473   * @param sources the sources to concatenate
474   * @return a {@code CharSource} containing the concatenated data
475   * @throws NullPointerException if any of {@code sources} is {@code null}
476   * @since 15.0
477   */
478  public static CharSource concat(Iterator<? extends CharSource> sources) {
479    return concat(ImmutableList.copyOf(sources));
480  }
481
482  /**
483   * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from
484   * the source will contain the concatenated data from the streams of the underlying sources.
485   *
486   * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will
487   * close the open underlying stream.
488   *
489   * @param sources the sources to concatenate
490   * @return a {@code CharSource} containing the concatenated data
491   * @throws NullPointerException if any of {@code sources} is {@code null}
492   * @since 15.0
493   */
494  public static CharSource concat(CharSource... sources) {
495    return concat(ImmutableList.copyOf(sources));
496  }
497
498  /**
499   * Returns a view of the given character sequence as a {@link CharSource}. The behavior of the
500   * returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if
501   * the {@code charSequence} is mutated while it is being read, so don't do that.
502   *
503   * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)})
504   */
505  public static CharSource wrap(CharSequence charSequence) {
506    return charSequence instanceof String
507        ? new StringCharSource((String) charSequence)
508        : new CharSequenceCharSource(charSequence);
509  }
510
511  /**
512   * Returns an immutable {@link CharSource} that contains no characters.
513   *
514   * @since 15.0
515   */
516  public static CharSource empty() {
517    return EmptyCharSource.INSTANCE;
518  }
519
520  /** A byte source that reads chars from this source and encodes them as bytes using a charset. */
521  private final class AsByteSource extends ByteSource {
522
523    final Charset charset;
524
525    AsByteSource(Charset charset) {
526      this.charset = checkNotNull(charset);
527    }
528
529    @Override
530    public CharSource asCharSource(Charset charset) {
531      if (charset.equals(this.charset)) {
532        return CharSource.this;
533      }
534      return super.asCharSource(charset);
535    }
536
537    @Override
538    public InputStream openStream() throws IOException {
539      return new ReaderInputStream(CharSource.this.openStream(), charset, 8192);
540    }
541
542    @Override
543    public String toString() {
544      return CharSource.this.toString() + ".asByteSource(" + charset + ")";
545    }
546  }
547
548  private static class CharSequenceCharSource extends CharSource {
549
550    private static final Splitter LINE_SPLITTER = Splitter.onPattern("\r\n|\n|\r");
551
552    protected final CharSequence seq;
553
554    protected CharSequenceCharSource(CharSequence seq) {
555      this.seq = checkNotNull(seq);
556    }
557
558    @Override
559    public Reader openStream() {
560      return new CharSequenceReader(seq);
561    }
562
563    @Override
564    public String read() {
565      return seq.toString();
566    }
567
568    @Override
569    public boolean isEmpty() {
570      return seq.length() == 0;
571    }
572
573    @Override
574    public long length() {
575      return seq.length();
576    }
577
578    @Override
579    public Optional<Long> lengthIfKnown() {
580      return Optional.of((long) seq.length());
581    }
582
583    /**
584     * Returns an iterator over the lines in the string. If the string ends in a newline, a final
585     * empty string is not included, to match the behavior of BufferedReader/LineReader.readLine().
586     */
587    private Iterator<String> linesIterator() {
588      return new AbstractIterator<String>() {
589        Iterator<String> lines = LINE_SPLITTER.split(seq).iterator();
590
591        @Override
592        @CheckForNull
593        protected String computeNext() {
594          if (lines.hasNext()) {
595            String next = lines.next();
596            // skip last line if it's empty
597            if (lines.hasNext() || !next.isEmpty()) {
598              return next;
599            }
600          }
601          return endOfData();
602        }
603      };
604    }
605
606    @Override
607    @SuppressWarnings("Java7ApiChecker")
608    // If users use this when they shouldn't, we hope that NewApi will catch subsequent Stream calls
609    @IgnoreJRERequirement
610    public Stream<String> lines() {
611      return stream(linesIterator());
612    }
613
614    @Override
615    @CheckForNull
616    public String readFirstLine() {
617      Iterator<String> lines = linesIterator();
618      return lines.hasNext() ? lines.next() : null;
619    }
620
621    @Override
622    public ImmutableList<String> readLines() {
623      return ImmutableList.copyOf(linesIterator());
624    }
625
626    @Override
627    @ParametricNullness
628    public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException {
629      Iterator<String> lines = linesIterator();
630      while (lines.hasNext()) {
631        if (!processor.processLine(lines.next())) {
632          break;
633        }
634      }
635      return processor.getResult();
636    }
637
638    @Override
639    public String toString() {
640      return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")";
641    }
642  }
643
644  /**
645   * Subclass specialized for string instances.
646   *
647   * <p>Since Strings are immutable and built into the jdk we can optimize some operations
648   *
649   * <ul>
650   *   <li>use {@link StringReader} instead of {@link CharSequenceReader}. It is faster since it can
651   *       use {@link String#getChars(int, int, char[], int)} instead of copying characters one by
652   *       one with {@link CharSequence#charAt(int)}.
653   *   <li>use {@link Appendable#append(CharSequence)} in {@link #copyTo(Appendable)} and {@link
654   *       #copyTo(CharSink)}. We know this is correct since strings are immutable and so the length
655   *       can't change, and it is faster because many writers and appendables are optimized for
656   *       appending string instances.
657   * </ul>
658   */
659  private static class StringCharSource extends CharSequenceCharSource {
660    protected StringCharSource(String seq) {
661      super(seq);
662    }
663
664    @Override
665    public Reader openStream() {
666      return new StringReader((String) seq);
667    }
668
669    @Override
670    public long copyTo(Appendable appendable) throws IOException {
671      appendable.append(seq);
672      return seq.length();
673    }
674
675    @Override
676    public long copyTo(CharSink sink) throws IOException {
677      checkNotNull(sink);
678      Closer closer = Closer.create();
679      try {
680        Writer writer = closer.register(sink.openStream());
681        writer.write((String) seq);
682        return seq.length();
683      } catch (Throwable e) {
684        throw closer.rethrow(e);
685      } finally {
686        closer.close();
687      }
688    }
689  }
690
691  private static final class EmptyCharSource extends StringCharSource {
692
693    private static final EmptyCharSource INSTANCE = new EmptyCharSource();
694
695    private EmptyCharSource() {
696      super("");
697    }
698
699    @Override
700    public String toString() {
701      return "CharSource.empty()";
702    }
703  }
704
705  private static final class ConcatenatedCharSource extends CharSource {
706
707    private final Iterable<? extends CharSource> sources;
708
709    ConcatenatedCharSource(Iterable<? extends CharSource> sources) {
710      this.sources = checkNotNull(sources);
711    }
712
713    @Override
714    public Reader openStream() throws IOException {
715      return new MultiReader(sources.iterator());
716    }
717
718    @Override
719    public boolean isEmpty() throws IOException {
720      for (CharSource source : sources) {
721        if (!source.isEmpty()) {
722          return false;
723        }
724      }
725      return true;
726    }
727
728    @Override
729    public Optional<Long> lengthIfKnown() {
730      long result = 0L;
731      for (CharSource source : sources) {
732        Optional<Long> lengthIfKnown = source.lengthIfKnown();
733        if (!lengthIfKnown.isPresent()) {
734          return Optional.absent();
735        }
736        result += lengthIfKnown.get();
737      }
738      return Optional.of(result);
739    }
740
741    @Override
742    public long length() throws IOException {
743      long result = 0L;
744      for (CharSource source : sources) {
745        result += source.length();
746      }
747      return result;
748    }
749
750    @Override
751    public String toString() {
752      return "CharSource.concat(" + sources + ")";
753    }
754  }
755}