001package org.unix4j.io;
002
003import org.unix4j.line.Line;
004import org.unix4j.line.SimpleLine;
005
006import java.util.Iterator;
007
008/**
009 * Input device based on a {@link Iterator} returning lines.
010 */
011public class IteratorInput extends AbstractInput {
012        private final Iterator<? extends Line> lines;
013
014        /**
015         * Constructor with linked list used as source of the input lines. The
016         * specified {@code buffer} is NOT cloned, meaning that changes to the
017         * buffer will also be reflected in this input device and vice versa.
018         *
019         * @param lines
020         *            the buffer to use as basis for this input device
021         */
022        public IteratorInput(Iterator<? extends Line> lines) {
023                this.lines = lines;
024        }
025
026        @Override
027        public boolean hasMoreLines() {
028                return lines.hasNext();
029        }
030
031        @Override
032        public Line readLine() {
033                if (lines.hasNext()) {
034                        final Line line = lines.next();
035                        if (lines.hasNext() && line.getLineEndingLength() == 0) {
036                                return new SimpleLine(line);// add line ending if not final line
037                        }
038                        return line;
039                }
040                return null;
041        }
042
043        /**
044         * Performs a no-op as there are no underlying resources
045         */
046        @Override
047        public void close() {
048                //nothing to do
049        }
050}