001package org.unix4j.io;
002
003import java.util.LinkedList;
004import java.util.List;
005
006import org.unix4j.line.Line;
007import org.unix4j.line.SimpleLine;
008import org.unix4j.util.LineUtil;
009
010/**
011 * Input device based on a {@link LinkedList} line buffer.
012 */
013public class BufferedInput extends AbstractInput {
014        private final LinkedList<Line> buffer;
015
016        /**
017         * Constructor with linked list used as source of the input lines. The
018         * specified {@code buffer} is NOT cloned, meaning that changes to the
019         * buffer will also be reflected in this input device and vice versa.
020         * 
021         * @param buffer
022         *            the buffer to use as basis for this input device
023         */
024        public BufferedInput(LinkedList<Line> buffer) {
025                this.buffer = buffer;
026        }
027
028        @Override
029        public boolean hasMoreLines() {
030                return !buffer.isEmpty();
031        }
032
033        @Override
034        public Line readLine() {
035                if (!buffer.isEmpty()) {
036                        final Line line = buffer.remove(0);
037                        if (!buffer.isEmpty() && line.getLineEndingLength() == 0) {
038                                return new SimpleLine(line);// add line ending if not final line
039                        }
040                        return line;
041                }
042                return null;
043        }
044
045        /**
046         * Returns a list-like representation of the lines contained in this buffer.
047         * Some users might also consider {@link #toMultiLineString()} instead.
048         * 
049         * @return a list-like string representation of the buffered lines
050         */
051        @Override
052        public String toString() {
053                return buffer.toString();
054        }
055
056        /**
057         * Returns a multi-line representation of the lines in this buffer. The last
058         * line is never terminated, all other lines are terminated with guarantee
059         * even if the line itself has an empty line ending string.
060         * 
061         * @return a multi-line string of the buffered lines, without line
062         *         termination for the last line
063         * @see LineUtil#toMultiLineString(List)
064         */
065        public String toMultiLineString() {
066                return LineUtil.toMultiLineString(buffer);
067        }
068
069        /**
070         * Performs a no-op as there are no underlying resources
071         */
072        @Override
073        public void close() {
074                //nothing to do
075        }
076}