Skip to content

Commit

Permalink
Implemented read(CharBuffer) to increase performance for that overloa…
Browse files Browse the repository at this point in the history
…d of read (#288)
  • Loading branch information
DavyLandman authored Jan 15, 2025
1 parent 08d8696 commit 54cf999
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1022,15 +1022,20 @@ public int read(char[] cbuf, int off, int len) throws IOException {
if (off < 0 || len < 0 || len > cbuf.length + off) {
throw new IndexOutOfBoundsException();
}
var target = CharBuffer.wrap(cbuf, off, len);
return read(CharBuffer.wrap(cbuf, off, len));
}

@Override
public int read(CharBuffer target) throws IOException {
int start = target.position();
while (target.hasRemaining()) {
var actualBuffer = getBuffer();
if (!actualBuffer.hasRemaining()) {
break;
}
actualBuffer.read(target);
}
return target.position() == off ? -1 : (len - target.remaining());
return target.position() == start ? -1 : target.position() - start;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.nio.CharBuffer;
import java.util.PrimitiveIterator.OfInt;
import java.util.Random;
import java.util.regex.Pattern;
Expand Down Expand Up @@ -402,14 +403,29 @@ private String readerSlowly(IString a) {

}

private String readerCharBufferToString(IString a) {
var buf = CharBuffer.allocate(a.length() * 2);
try (var r = a.asReader()) {
while (r.read(buf) != -1) ;
buf.flip();
return buf.toString();
} catch (IOException e) {
fail("IString::asReader failed", e);
return "";
}
}


private void assertEqualWriteAndRead(IString one, IString two) {
assertEquals(one.length(), two.length(), "IString::length should be equal");
assertEquals(one.getValue(), writerToString(one), "IString::write should be the same as getValue");
assertEquals(one.getValue(), readerToString(one), "IString::asReader should be the same as getValue");
assertEquals(writerToString(one), writerToString(two), "IString::write had different results");
assertEquals(readerToString(one), readerToString(two), "IString::asReader had different results");
assertEquals(one.getValue(), readerSlowly(one), "IString::asReader had different results depending on buffer size");
assertEquals(two.getValue(), readerSlowly(two), "IString::asReader had different results depending on buffer size");
assertEquals(one.getValue(), readerCharBufferToString(one), "IString::asReader had different results when using char buffer read");
assertEquals(two.getValue(), readerCharBufferToString(two), "IString::asReader had different results when using char buffer read");
}

private void assertEqualCharAt(IString one, IString two) {
Expand Down

0 comments on commit 54cf999

Please sign in to comment.