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) throws IOException {
076 if (string == null) {
077 throw new IOException("String is null");
078 }
079
080 if (length <= 0) {
081 return 0;
082 }
083
084 if (index >= stringLength) {
085 return -1;
086 }
087
088 int read = length;
089
090 if ((index + read) > stringLength) {
091 read = stringLength - index;
092 }
093
094 string.getChars(index, index + read, chars, offset);
095
096 index += read;
097
098 return read;
099 }
100
101 @Override
102 public int read(CharBuffer charBuffer) throws IOException {
103 int remaining = charBuffer.remaining();
104
105 char[] chars = new char[remaining];
106
107 int read = read(chars, 0, remaining);
108
109 if (read > 0) {
110 charBuffer.put(chars, 0, read);
111 }
112
113 return read;
114 }
115
116 @Override
117 public boolean ready() throws IOException {
118 if (string == null) {
119 throw new IOException("String is null");
120 }
121
122 return true;
123 }
124
125 @Override
126 public void reset() throws IOException {
127 if (string == null) {
128 throw new IOException("String is null");
129 }
130
131 index = markIndex;
132 }
133
134 @Override
135 public long skip(long skip) {
136 if (index >= stringLength) {
137 return 0;
138 }
139
140 if ((skip + index) > stringLength) {
141 skip = stringLength - index;
142 }
143
144 index += skip;
145
146 return skip;
147 }
148
149 protected int index;
150 protected int markIndex;
151 protected String string;
152 protected int stringLength;
153
154 }