Skip to content

Commit

Permalink
Do not rewind position when serializing direct ByteBuffer (#4164)
Browse files Browse the repository at this point in the history
ByteBufferSerializer considers the position when serializing heap buffers, but ignores it (by rewinding) for direct buffers. I believe the former behavior is correct, so I've aligned the direct buffer code with that.
  • Loading branch information
yawkat committed Oct 17, 2023
1 parent 8146fa8 commit 1126dff
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,8 @@ public void serialize(ByteBuffer bbuf, JsonGenerator gen, SerializerProvider pro
return;
}
// the other case is more complicated however. Best to handle with InputStream wrapper.
// But should we rewind it; and/or make a copy?
// Prior to jackson-databind#4164 we rewound here, but that didn't match heap buffer behavior.
ByteBuffer copy = bbuf.asReadOnlyBuffer();
if (copy.position() > 0) {
copy.rewind();
}
InputStream in = new ByteBufferBackedInputStream(copy);
gen.writeBinary(in, copy.remaining());
in.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ public void testByteBuffer() throws IOException
// so far so good, but must ensure Native buffers also work:
ByteBuffer bbuf2 = ByteBuffer.allocateDirect(5);
bbuf2.put(INPUT_BYTES);
bbuf2.flip();
assertEquals(exp, MAPPER.writeValueAsString(bbuf2));
}

Expand Down Expand Up @@ -182,6 +183,18 @@ public void testDuplicatedByteBufferWithCustomPosition() throws IOException
assertEquals(exp, MAPPER.writeValueAsString(bbuf.duplicate()));
}

public void testDuplicatedByteBufferWithCustomPositionDirect() throws IOException
{
final byte[] INPUT_BYTES = new byte[] { 1, 2, 3, 4, 5 };

String exp = MAPPER.writeValueAsString(new byte[] { 3, 4, 5 });
ByteBuffer bbuf = ByteBuffer.allocateDirect(INPUT_BYTES.length);
bbuf.put(INPUT_BYTES);
bbuf.position(2);
ByteBuffer duplicated = bbuf.duplicate();
assertEquals(exp, MAPPER.writeValueAsString(duplicated));
}

// [databind#2197]
public void testVoidSerialization() throws Exception
{
Expand Down

0 comments on commit 1126dff

Please sign in to comment.