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.checkNotNull;
018import static com.google.common.io.CharStreams.createBuffer;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import java.io.IOException;
024import java.io.Reader;
025import java.nio.CharBuffer;
026import java.util.ArrayDeque;
027import java.util.Queue;
028import javax.annotation.CheckForNull;
029
030/**
031 * A class for reading lines of text. Provides the same functionality as {@link
032 * java.io.BufferedReader#readLine()} but for all {@link Readable} objects, not just instances of
033 * {@link Reader}.
034 *
035 * @author Chris Nokleberg
036 * @since 1.0
037 */
038@J2ktIncompatible
039@GwtIncompatible
040@ElementTypesAreNonnullByDefault
041public final class LineReader {
042  private final Readable readable;
043  @CheckForNull private final Reader reader;
044  private final CharBuffer cbuf = createBuffer();
045  private final char[] buf = cbuf.array();
046
047  private final Queue<String> lines = new ArrayDeque<>();
048  private final LineBuffer lineBuf =
049      new LineBuffer() {
050        @Override
051        protected void handleLine(String line, String end) {
052          lines.add(line);
053        }
054      };
055
056  /** Creates a new instance that will read lines from the given {@code Readable} object. */
057  public LineReader(Readable readable) {
058    this.readable = checkNotNull(readable);
059    this.reader = (readable instanceof Reader) ? (Reader) readable : null;
060  }
061
062  /**
063   * Reads a line of text. A line is considered to be terminated by any one of a line feed ({@code
064   * '\n'}), a carriage return ({@code '\r'}), or a carriage return followed immediately by a
065   * linefeed ({@code "\r\n"}).
066   *
067   * @return a {@code String} containing the contents of the line, not including any
068   *     line-termination characters, or {@code null} if the end of the stream has been reached.
069   * @throws IOException if an I/O error occurs
070   */
071  @CanIgnoreReturnValue // to skip a line
072  @CheckForNull
073  public String readLine() throws IOException {
074    while (lines.peek() == null) {
075      Java8Compatibility.clear(cbuf);
076      // The default implementation of Reader#read(CharBuffer) allocates a
077      // temporary char[], so we call Reader#read(char[], int, int) instead.
078      int read = (reader != null) ? reader.read(buf, 0, buf.length) : readable.read(cbuf);
079      if (read == -1) {
080        lineBuf.finish();
081        break;
082      }
083      lineBuf.add(buf, 0, read);
084    }
085    return lines.poll();
086  }
087}