Skip to content

Commit 1126dff

Browse files
authored
Do not rewind position when serializing direct ByteBuffer (#4164)
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.
1 parent 8146fa8 commit 1126dff

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/main/java/com/fasterxml/jackson/databind/ser/std/ByteBufferSerializer.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,8 @@ public void serialize(ByteBuffer bbuf, JsonGenerator gen, SerializerProvider pro
2525
return;
2626
}
2727
// the other case is more complicated however. Best to handle with InputStream wrapper.
28-
// But should we rewind it; and/or make a copy?
28+
// Prior to jackson-databind#4164 we rewound here, but that didn't match heap buffer behavior.
2929
ByteBuffer copy = bbuf.asReadOnlyBuffer();
30-
if (copy.position() > 0) {
31-
copy.rewind();
32-
}
3330
InputStream in = new ByteBufferBackedInputStream(copy);
3431
gen.writeBinary(in, copy.remaining());
3532
in.close();

src/test/java/com/fasterxml/jackson/databind/ser/jdk/JDKTypeSerializationTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ public void testByteBuffer() throws IOException
143143
// so far so good, but must ensure Native buffers also work:
144144
ByteBuffer bbuf2 = ByteBuffer.allocateDirect(5);
145145
bbuf2.put(INPUT_BYTES);
146+
bbuf2.flip();
146147
assertEquals(exp, MAPPER.writeValueAsString(bbuf2));
147148
}
148149

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

186+
public void testDuplicatedByteBufferWithCustomPositionDirect() throws IOException
187+
{
188+
final byte[] INPUT_BYTES = new byte[] { 1, 2, 3, 4, 5 };
189+
190+
String exp = MAPPER.writeValueAsString(new byte[] { 3, 4, 5 });
191+
ByteBuffer bbuf = ByteBuffer.allocateDirect(INPUT_BYTES.length);
192+
bbuf.put(INPUT_BYTES);
193+
bbuf.position(2);
194+
ByteBuffer duplicated = bbuf.duplicate();
195+
assertEquals(exp, MAPPER.writeValueAsString(duplicated));
196+
}
197+
185198
// [databind#2197]
186199
public void testVoidSerialization() throws Exception
187200
{

0 commit comments

Comments
 (0)