Skip to content

Commit 07da78b

Browse files
committed
Fix writeRaw(String, offset, len) to copy only the requested slice
Use getChars(offset, offset+len) instead of toCharArray() which copies the entire string unnecessarily.
1 parent 0887616 commit 07da78b

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

msgpack-jackson3/src/main/java/org/msgpack/jackson/dataformat/MessagePackGenerator.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -677,8 +677,9 @@ public JsonGenerator writeRaw(String text) throws JacksonException
677677
public JsonGenerator writeRaw(String text, int offset, int len) throws JacksonException
678678
{
679679
try {
680-
char[] chars = text.toCharArray();
681-
writeCharArrayTextValue(chars, offset, len);
680+
char[] chars = new char[len];
681+
text.getChars(offset, offset + len, chars, 0);
682+
writeCharArrayTextValue(chars, 0, len);
682683
}
683684
catch (IOException e) {
684685
throw _wrapIOFailure(e);

msgpack-jackson3/src/test/java/org/msgpack/jackson/dataformat/MessagePackGeneratorTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -996,6 +996,22 @@ public void testGeneratorReusableAfterRootContainerClose()
996996
assertEquals(2, unpacker.unpackInt());
997997
}
998998

999+
@Test
1000+
public void testWriteRawStringWithOffset()
1001+
throws IOException
1002+
{
1003+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
1004+
JsonGenerator generator = factory.createGenerator(baos, JsonEncoding.UTF8);
1005+
generator.writeStartArray();
1006+
generator.writeRaw("XXhelloXX", 2, 5); // "hello"
1007+
generator.writeEndArray();
1008+
generator.close();
1009+
1010+
MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(baos.toByteArray());
1011+
unpacker.unpackArrayHeader();
1012+
assertEquals("hello", unpacker.unpackString());
1013+
}
1014+
9991015
@Test
10001016
public void testWriteStringCharArrayWithOffset()
10011017
throws IOException

0 commit comments

Comments
 (0)