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
029 public class UnsyncStringReader extends Reader {
030
031 public UnsyncStringReader(String string) {
032 this.string = string;
033
034 stringLength = string.length();
035 }
036
037 @Override
038 public void close() {
039 string = null;
040 }
041
042 @Override
043 public void mark(int readAheadLimit) throws IOException {
044 if (string == null) {
045 throw new IOException("String is null");
046 }
047
048 markIndex = index;
049 }
050
051 @Override
052 public boolean markSupported() {
053 return true;
054 }
055
056 @Override
057 public int read() throws IOException {
058 if (string == null) {
059 throw new IOException("String is null");
060 }
061
062 if (index >= stringLength) {
063 return -1;
064 }
065
066 return string.charAt(index++);
067 }
068
069 @Override
070 public int read(char[] chars) throws IOException {
071 return read(chars, 0, chars.length);
072 }
073
074 @Override
075 public int read(char[] chars, int offset, int length)
076 throws IOException {
077
078 if (string == null) {
079 throw new IOException("String is null");
080 }
081
082 if (length <= 0) {
083 return 0;
084 }
085
086 if (index >= stringLength) {
087 return -1;
088 }
089
090 int read = length;
091
092 if ((index + read) > stringLength) {
093 read = stringLength - index;
094 }
095
096 string.getChars(index, index + read, chars, offset);
097
098 index += read;
099
100 return read;
101 }
102
103 @Override
104 public int read(CharBuffer charBuffer) throws IOException {
105 int remaining = charBuffer.remaining();
106
107 char[] chars = new char[remaining];
108
109 int read = read(chars, 0, remaining);
110
111 if (read > 0) {
112 charBuffer.put(chars, 0, read);
113 }
114
115 return read;
116 }
117
118 @Override
119 public boolean ready() throws IOException {
120 if (string == null) {
121 throw new IOException("String is null");
122 }
123
124 return true;
125 }
126
127 @Override
128 public void reset() throws IOException {
129 if (string == null) {
130 throw new IOException("String is null");
131 }
132
133 index = markIndex;
134 }
135
136 @Override
137 public long skip(long skip) {
138 if (index >= stringLength) {
139 return 0;
140 }
141
142 if ((skip + index) > stringLength) {
143 skip = stringLength - index;
144 }
145
146 index += skip;
147
148 return skip;
149 }
150
151 protected int index;
152 protected int markIndex;
153 protected String string;
154 protected int stringLength;
155
156 }