1
14
15 package com.liferay.portal.kernel.io.unsync;
16
17 import java.io.IOException;
18 import java.io.Reader;
19
20 import java.nio.CharBuffer;
21
22
27 public class UnsyncCharArrayReader extends Reader {
28
29 public UnsyncCharArrayReader(char[] charArray) {
30 buffer = charArray;
31 capacity = charArray.length;
32 index = 0;
33 }
34
35 public UnsyncCharArrayReader(char[] charArray, int offset, int length) {
36 buffer = charArray;
37 capacity = Math.min(charArray.length, offset + length);
38 index = offset;
39 markIndex = offset;
40 }
41
42 public void close() {
43 buffer = null;
44 }
45
46 public void mark(int readAheadLimit) throws IOException {
47 if (buffer == null) {
48 throw new IOException("Stream closed");
49 }
50 markIndex = index;
51 }
52
53 public boolean markSupported() {
54 return true;
55 }
56
57 public int read() throws IOException {
58 if (buffer == null) {
59 throw new IOException("Stream closed");
60 }
61
62 if (index >= capacity) {
63 return -1;
64 }
65 else {
66 return buffer[index++];
67 }
68 }
69
70 public int read(char[] charArray) throws IOException {
71 return read(charArray, 0, charArray.length);
72 }
73
74 public int read(char[] charArray, int offset, int length)
75 throws IOException {
76
77 if (buffer == null) {
78 throw new IOException("Stream closed");
79 }
80
81 if (length <= 0) {
82 return 0;
83 }
84
85 if (index >= capacity) {
86 return -1;
87 }
88
89 int read = length;
90
91 if ((index + read) > capacity) {
92 read = capacity - index;
93 }
94
95 System.arraycopy(buffer, index, charArray, offset, read);
96
97 index += read;
98
99 return read;
100 }
101
102 public int read(CharBuffer charBuffer) throws IOException {
103 if (buffer == null) {
104 throw new IOException("Stream closed");
105 }
106
107 int length = charBuffer.remaining();
108
109 if (length <= 0) {
110 return 0;
111 }
112
113 if (index >= capacity) {
114 return -1;
115 }
116
117 if ((index + length) > capacity) {
118 length = capacity - index;
119 }
120
121 charBuffer.put(buffer, index, length);
122
123 index += length;
124
125 return length;
126 }
127
128 public boolean ready() throws IOException {
129 if (buffer == null) {
130 throw new IOException("Stream closed");
131 }
132
133 if (capacity > index) {
134 return true;
135 }
136 else {
137 return false;
138 }
139 }
140
141 public void reset() throws IOException {
142 if (buffer == null) {
143 throw new IOException("Stream closed");
144 }
145
146 index = markIndex;
147 }
148
149 public long skip(long skip) throws IOException {
150 if (buffer == null) {
151 throw new IOException("Stream closed");
152 }
153
154 if (skip < 0) {
155 return 0;
156 }
157
158 if (index + skip > capacity) {
159 skip = capacity - index;
160 }
161
162 index += skip;
163
164 return skip;
165 }
166
167 protected char[] buffer;
168 protected int capacity;
169 protected int index;
170 protected int markIndex;
171
172 }