Skip to content

Commit 97e0751

Browse files
committed
Fix writeString(Reader, int) to avoid large upfront allocation
When a non-negative length hint is supplied, the previous code allocated new char[len] upfront — an unbounded allocation if the caller passed a large value. Replace it with chunked reading (8192-char buffer) into a StringBuilder, matching the pattern already used in the len<0 branch.
1 parent 5a774c4 commit 97e0751

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -591,16 +591,19 @@ public JsonGenerator writeString(Reader reader, int len) throws JacksonException
591591
addValueNode(sb.toString());
592592
}
593593
else {
594-
char[] buf = new char[len];
595-
int totalRead = 0;
596-
while (totalRead < len) {
597-
int read = reader.read(buf, totalRead, len - totalRead);
594+
int chunkSize = Math.min(len, 8192);
595+
StringBuilder sb = new StringBuilder(chunkSize);
596+
char[] tmpBuf = new char[chunkSize];
597+
int remaining = len;
598+
while (remaining > 0) {
599+
int read = reader.read(tmpBuf, 0, Math.min(remaining, tmpBuf.length));
598600
if (read < 0) {
599601
break;
600602
}
601-
totalRead += read;
603+
sb.append(tmpBuf, 0, read);
604+
remaining -= read;
602605
}
603-
writeCharArrayTextValue(buf, 0, totalRead);
606+
addValueNode(sb.toString());
604607
}
605608
}
606609
catch (IOException e) {

0 commit comments

Comments
 (0)