1package tests.support;
2
3import java.io.IOException;
4import java.io.Reader;
5
6/**
7 * An implementation of {@code Reader} that should serve as the
8 * underlying writer for classes to be tested.
9 * In particular this implementation allows to have IOExecptions thrown on demand.
10 * For simplicity of use and understanding all fields are public.
11 */
12public class Support_ASimpleReader extends Reader {
13
14    public static final int DEFAULT_BUFFER_SIZE = 32;
15
16    public char[] buf;
17
18    public int pos;
19
20    public int len;
21
22    // Set to true when exception is wanted:
23    public boolean throwExceptionOnNextUse = false;
24
25    public Support_ASimpleReader() {
26        this("BEGIN Bla bla, some text...END");
27    }
28
29    public Support_ASimpleReader(boolean throwException) {
30        this();
31        throwExceptionOnNextUse = throwException;
32    }
33
34    public Support_ASimpleReader(String input) {
35        buf = input.toCharArray();
36        pos = 0;
37        len = buf.length;
38    }
39
40    @Override
41    public void close() throws IOException {
42        if (throwExceptionOnNextUse) {
43            throw new IOException("Exception thrown for testing purpose.");
44        }
45    }
46
47    @Override
48    public boolean ready() throws IOException {
49        if (throwExceptionOnNextUse) {
50            throw new IOException("Exception thrown for testing purpose.");
51        }
52        return len > pos;
53    }
54
55    @Override
56    public int read(char[] dest, int offset, int count) throws IOException {
57        if (throwExceptionOnNextUse) {
58            throw new IOException("Exception thrown for testing purpose.");
59        }
60        int available = len - pos;
61        if (available > 0) {
62            int readable = (available < count ? available : count);
63            System.arraycopy(buf, pos, dest, offset, readable);
64            pos += readable;
65            return readable;
66        } else {
67            return -1;
68        }
69    }
70}
71