aboutsummaryrefslogtreecommitdiff
path: root/src/rejava/io/StringReader.java
blob: 65a1aba6a39781ee8039e85be0c988a440b1c575 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package rejava.io;

/**
 * A minimal subset of java.io.StringReader.
 * (http://hg.openjdk.java.net/jdk7/jdk7
 * /jdk/file/9b8c96f96a0f/src/share/classes/java/io/StringReader.java)
 * 
 * @author Pacien TRAN-GIRARD
 */
public class StringReader extends Reader {

	private final String str;
	private int index;

	public StringReader(final String str) {
		this.str = str;
	}

	@Override
	public int read() {
		if (this.str == null) {
			return -1;
		}
		if (this.index >= this.str.length()) {
			return -1;
		}
		this.index++;
		return this.str.charAt(this.index);
	}

	@Override
	public int read(final char[] cbuf, final int off, final int len) {
		if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length)
				|| ((off + len) < 0)) {
			throw new IndexOutOfBoundsException();
		}
		if (len == 0) {
			return 0;
		}
		if (this.str == null) {
			return -1;
		}
		if (this.index >= this.str.length()) {
			return -1;
		}
		final int n = Math.min(this.str.length() - this.index, len);
		this.str.getChars(this.index, this.index + n, cbuf, off);
		this.index += n;
		return n;
	}

}