1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.mercury.common.io;
14
15 import java.io.IOException;
16 import java.io.Reader;
17
18
19
20
21
22
23 public class StringBufferReader extends Reader {
24
25
26 protected StringBuffer buffer;
27
28
29 protected int ptr;
30
31
32 protected int mark = 0;
33
34
35 protected int size;
36
37
38
39
40
41 public StringBufferReader(StringBuffer buffer) {
42 this.buffer = buffer;
43 size = buffer.length();
44 }
45
46
47
48
49
50
51
52 public StringBufferReader(StringBuffer buffer, int from, int size) {
53 this.buffer = buffer;
54 ptr = from;
55 size = ptr+size;
56 if (ptr > buffer.length()) {
57 ptr = buffer.length();
58 }
59 if (size > buffer.length()) {
60 size = buffer.length();
61 }
62 if (size < ptr) {
63 size = ptr;
64 }
65 }
66
67 @Override
68 public int read(char[] cbuf, int off, int len) throws IOException {
69 if (ptr >= buffer.length()) {
70 return -1;
71 }
72 if (len > size-ptr) {
73 len = size-ptr;
74 }
75 if (len == 0) {
76 return 0;
77 }
78 buffer.getChars(ptr, ptr+len, cbuf, off);
79 ptr = ptr + len;
80 return len;
81 }
82
83 @Override
84 public void close() throws IOException {
85 }
86
87 @Override
88 public boolean markSupported() {
89 return true;
90 }
91
92
93
94
95 public void mark() {
96 mark = ptr;
97 }
98
99 @Override
100 public void reset() {
101 ptr = mark;
102 }
103
104 @Override
105 public boolean ready() {
106 return true;
107 }
108
109 @Override
110 public long skip(long n) {
111 if (n > size - ptr) {
112 n = size - ptr;
113 }
114 ptr = ptr + (int)n;
115 return n;
116 }
117
118 }