001
014
015 package com.liferay.portal.kernel.io.unsync;
016
017 import java.io.IOException;
018 import java.io.Reader;
019
020 import java.nio.CharBuffer;
021
022
025 public class UnsyncCharArrayReader extends Reader {
026
027 public UnsyncCharArrayReader(char[] charArray) {
028 buffer = charArray;
029 capacity = charArray.length;
030 index = 0;
031 }
032
033 public UnsyncCharArrayReader(char[] charArray, int offset, int length) {
034 buffer = charArray;
035 capacity = Math.min(charArray.length, offset + length);
036 index = offset;
037 markIndex = offset;
038 }
039
040 public void close() {
041 buffer = null;
042 }
043
044 public void mark(int readAheadLimit) throws IOException {
045 if (buffer == null) {
046 throw new IOException("Stream closed");
047 }
048 markIndex = index;
049 }
050
051 public boolean markSupported() {
052 return true;
053 }
054
055 public int read() throws IOException {
056 if (buffer == null) {
057 throw new IOException("Stream closed");
058 }
059
060 if (index >= capacity) {
061 return -1;
062 }
063 else {
064 return buffer[index++];
065 }
066 }
067
068 public int read(char[] charArray) throws IOException {
069 return read(charArray, 0, charArray.length);
070 }
071
072 public int read(char[] charArray, int offset, int length)
073 throws IOException {
074
075 if (buffer == null) {
076 throw new IOException("Stream closed");
077 }
078
079 if (length <= 0) {
080 return 0;
081 }
082
083 if (index >= capacity) {
084 return -1;
085 }
086
087 int read = length;
088
089 if ((index + read) > capacity) {
090 read = capacity - index;
091 }
092
093 System.arraycopy(buffer, index, charArray, offset, read);
094
095 index += read;
096
097 return read;
098 }
099
100 public int read(CharBuffer charBuffer) throws IOException {
101 if (buffer == null) {
102 throw new IOException("Stream closed");
103 }
104
105 int length = charBuffer.remaining();
106
107 if (length <= 0) {
108 return 0;
109 }
110
111 if (index >= capacity) {
112 return -1;
113 }
114
115 if ((index + length) > capacity) {
116 length = capacity - index;
117 }
118
119 charBuffer.put(buffer, index, length);
120
121 index += length;
122
123 return length;
124 }
125
126 public boolean ready() throws IOException {
127 if (buffer == null) {
128 throw new IOException("Stream closed");
129 }
130
131 if (capacity > index) {
132 return true;
133 }
134 else {
135 return false;
136 }
137 }
138
139 public void reset() throws IOException {
140 if (buffer == null) {
141 throw new IOException("Stream closed");
142 }
143
144 index = markIndex;
145 }
146
147 public long skip(long skip) throws IOException {
148 if (buffer == null) {
149 throw new IOException("Stream closed");
150 }
151
152 if (skip < 0) {
153 return 0;
154 }
155
156 if (index + skip > capacity) {
157 skip = capacity - index;
158 }
159
160 index += skip;
161
162 return skip;
163 }
164
165 protected char[] buffer;
166 protected int capacity;
167 protected int index;
168 protected int markIndex;
169
170 }