This commit is contained in:
Andrea Cavalli 2024-09-25 20:02:12 +02:00
parent a06ddc7d0a
commit 70adaaf6cf
2 changed files with 19 additions and 7 deletions

View File

@ -19,13 +19,13 @@ public class BufDataOutput implements SafeDataOutput {
private final SafeDataOutputStream dOut;
private final int limit;
private BufDataOutput(SafeByteArrayOutputStream buf) {
public BufDataOutput(SafeByteArrayOutputStream buf) {
this.buf = buf;
this.dOut = new SafeDataOutputStream(buf);
limit = Integer.MAX_VALUE;
}
private BufDataOutput(SafeByteArrayOutputStream buf, int maxSize) {
public BufDataOutput(SafeByteArrayOutputStream buf, int maxSize) {
this.buf = buf;
this.dOut = new SafeDataOutputStream(buf);
this.limit = maxSize;
@ -219,13 +219,12 @@ public class BufDataOutput implements SafeDataOutput {
public void writeShortText(String s, Charset charset) {
if (charset == StandardCharsets.UTF_8) {
var beforeWrite = this.buf.position();
this.buf.position(beforeWrite + Short.BYTES);
writeShort(0);
ZeroAllocationEncoder.INSTANCE.encodeTo(s, this);
var afterWrite = this.buf.position();
this.buf.position(beforeWrite);
var len = Math.toIntExact(afterWrite - beforeWrite - Short.BYTES);
if (len > Short.MAX_VALUE) {
this.buf.position(beforeWrite);
throw new IndexOutOfBoundsException("String too long: " + len + " bytes");
}
this.writeShort(len);
@ -245,7 +244,7 @@ public class BufDataOutput implements SafeDataOutput {
public void writeMediumText(String s, Charset charset) {
if (charset == StandardCharsets.UTF_8) {
var beforeWrite = this.buf.position();
this.buf.position(beforeWrite + Integer.BYTES);
writeInt(0);
ZeroAllocationEncoder.INSTANCE.encodeTo(s, this);
var afterWrite = this.buf.position();
this.buf.position(beforeWrite);

View File

@ -71,11 +71,24 @@ class ZeroAllocationEncoderTest {
testDecodeString("lorem ipsum dolor sit amet my name is giovanni");
}
@Test
void encodeToLong() {
testEncodeString("lorem ipsum dolor sit amet ".repeat(10));
}
@Test
void decodeLong() {
testDecodeString("lorem ipsum dolor sit amet".repeat(10));
}
public void testEncodeString(String s) {
var bdo = BufDataOutput.create();
INSTANCE.encodeTo(s, bdo);
var out = bdo.toList().toString(StandardCharsets.UTF_8);
Assertions.assertEquals(s, out);
var out = bdo.toList();
out.toString(StandardCharsets.UTF_8);
Assertions.assertEquals(s, out.toString(StandardCharsets.UTF_8));
Assertions.assertEquals(s.length(), bdo.size());
Assertions.assertEquals(s.length(), out.size());
}
private void testDecodeString(String s) {