From c758be6019b8384bbf46b6903587b7bd703ba440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=AB=98=E9=93=81?= Date: Tue, 13 Aug 2024 19:09:31 +0800 Subject: [PATCH] fix csv write ArrayIndexOutOfBoundsException error, for issue #2848 --- .../fastjson2/support/csv/CSVWriterUTF16.java | 6 ++++ .../fastjson2/support/csv/CSVWriterUTF8.java | 6 ++++ .../fastjson2/issues_2800/Issue2848.java | 34 +++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2848.java diff --git a/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF16.java b/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF16.java index c136a8249d..b715877b73 100644 --- a/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF16.java +++ b/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF16.java @@ -216,6 +216,12 @@ public void writeDecimal(BigDecimal value) { String str = value.toString(); int strlen = str.length(); + + int minCapacity = off + 24; + if (minCapacity - this.chars.length > 0) { + flush(); + } + str.getChars(0, strlen, chars, off); off += strlen; } diff --git a/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF8.java b/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF8.java index 763a1072b1..88de07c319 100644 --- a/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF8.java +++ b/core/src/main/java/com/alibaba/fastjson2/support/csv/CSVWriterUTF8.java @@ -219,6 +219,12 @@ public void writeDecimal(BigDecimal value) { String str = value.toString(); int strlen = str.length(); + + int minCapacity = off + 24; + if (minCapacity - this.bytes.length > 0) { + flush(); + } + str.getBytes(0, strlen, bytes, off); off += strlen; } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2848.java b/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2848.java new file mode 100644 index 0000000000..99aa5fcc32 --- /dev/null +++ b/core/src/test/java/com/alibaba/fastjson2/issues_2800/Issue2848.java @@ -0,0 +1,34 @@ +package com.alibaba.fastjson2.issues_2800; + +import com.alibaba.fastjson2.support.csv.CSVWriter; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; + +public class Issue2848 { + @Test + public void test() throws Exception { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 65531; i++) { + buf.append('1'); + } + + String str = buf.toString(); + + try (CSVWriter writer = CSVWriter.of()) { + writer.writeValue(str); + writer.writeComma(); + writer.writeValue(new BigDecimal("1.00")); + writer.writeComma(); + } + + try (CSVWriter writer = CSVWriter.of(new ByteArrayOutputStream(), StandardCharsets.UTF_16)) { + writer.writeValue(str); + writer.writeComma(); + writer.writeValue(new BigDecimal("1.00")); + writer.writeComma(); + } + } +}