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