<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import java.io.InputStream;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class IterableStreamSolution extends IterableStream {
	/** Underlying stream */
	private InputStream stream;

	/**
	 * Create a new iterable stream
	 * 
	 * @param s The stream to wrap
	 */
	public IterableStreamSolution(InputStream s) {
		super(s);
		stream = s;
	}

	@Override
	public Iterator&lt;Byte&gt; iterator() {
		return new ByteStreamIteratorSolution();
	}

	/**
	 * An iterator over an iterable stream. Will read from the stream, so it is not
	 * safe to read from the stream outside of this iterator, or to create multiple
	 * iterators wrapping the same stream.
	 */
	private class ByteStreamIteratorSolution implements Iterator&lt;Byte&gt; {

		/**
		 * Next byte in the stream, if ready and not at end of stream
		 */
		byte nxt;

		/**
		 * Whether the stream is at the end, if ready
		 */
		boolean eos;

		/**
		 * Whether {@code nxt} and {@code eos} contain the next byte
		 */
		boolean ready;

		/**
		 * Construct a new stream iterator.
		 */
		public ByteStreamIteratorSolution() {
		}

		/**
		 * Read the next byte from the stream and set {@code nxt} and {@code eos}
		 * appropriately.
		 */
		private void advance() {
			int b;
			try {
				b = stream.read();
			} catch (java.io.IOException e) {
				eos = true;
				ready = true;
				return;
			}

			ready = true;
			if (b == -1) {
				eos = true;
				return;
			}
			if (b &lt;= 127) {
				nxt = (byte) b;
			} else {
				nxt = (byte) (b - 256);
			}
		}

		@Override
		public boolean hasNext() {
			if (!ready) {
				advance();
			}
			return !eos;
		}

		@Override
		public Byte next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}
			ready = false;
			return nxt;
		}
	}
}
</pre></body></html>