com.github.azbh111.utils.java.string.model.CharSequenceReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-java Show documentation
Show all versions of utils-java Show documentation
com.github.azbh111:utils-java
The newest version!
package com.github.azbh111.utils.java.string.model;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.Objects;
/**
* @author: zyp
* @since: 2021/12/14 下午2:49
*/
public class CharSequenceReader extends Reader {
private CharSequence seq;
private int pos;
private int mark;
public CharSequenceReader(CharSequence seq) {
this.seq = Objects.requireNonNull(seq);
}
private boolean hasRemaining() {
return remaining() > 0;
}
private int remaining() {
return seq.length() - pos;
}
@Override
public synchronized int read(CharBuffer target) throws IOException {
if (!hasRemaining()) {
return -1;
}
int c = Math.min(target.remaining(), remaining());
for (int i = 0; i < c; i++) {
target.put(seq.charAt(pos++));
}
return c;
}
@Override
public synchronized int read() throws IOException {
return hasRemaining() ? seq.charAt(pos++) : -1;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if (!hasRemaining()) {
return -1;
}
int c = Math.min(len, remaining());
for (int i = 0; i < c; i++) {
cbuf[off + i] = seq.charAt(pos++);
}
return c;
}
@Override
public long skip(long n) throws IOException {
int skip = (int) Math.min(remaining(), n);
pos += skip;
return skip;
}
@Override
public boolean ready() throws IOException {
return true;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit) throws IOException {
mark = pos;
}
@Override
public void reset() throws IOException {
pos = mark;
}
@Override
public void close() throws IOException {
}
}