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.Beta;
021import com.google.common.annotations.GwtIncompatible;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import java.io.IOException;
024import java.io.Reader;
025import java.nio.CharBuffer;
026import java.util.LinkedList;
027import java.util.Queue;
028
029/**
030 * A class for reading lines of text. Provides the same functionality as
031 * {@link java.io.BufferedReader#readLine()} but for all {@link Readable} objects, not just
032 * instances of {@link Reader}.
033 *
034 * @author Chris Nokleberg
035 * @since 1.0
036 */
037@Beta
038@GwtIncompatible
039public final class LineReader {
040  private final Readable readable;
041  private final Reader reader;
042  private final CharBuffer cbuf = createBuffer();
043  private final char[] buf = cbuf.array();
044
045  private final Queue<String> lines = new LinkedList<>();
046  private final LineBuffer lineBuf =
047      new LineBuffer() {
048        @Override
049        protected void handleLine(String line, String end) {
050          lines.add(line);
051        }
052      };
053
054  /**
055   * Creates a new instance that will read lines from the given {@code Readable} object.
056   */
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
064   * ({@code '\n'}), a carriage return ({@code '\r'}), or a carriage return followed immediately by
065   * a 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  public String readLine() throws IOException {
073    while (lines.peek() == null) {
074      cbuf.clear();
075      // The default implementation of Reader#read(CharBuffer) allocates a
076      // temporary char[], so we call Reader#read(char[], int, int) instead.
077      int read = (reader != null)
078          ? reader.read(buf, 0, buf.length)
079          : readable.read(cbuf);
080      if (read == -1) {
081        lineBuf.finish();
082        break;
083      }
084      lineBuf.add(buf, 0, read);
085    }
086    return lines.poll();
087  }
088}