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