From 65d6d1101c84ddd6fdfa4ef00db5da0385a57805 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Mon, 11 Mar 2024 16:04:00 -0400 Subject: [PATCH] Allocate a string look ahead buffer in CSVFormat.printWithEscapes(CharSequence, Appendable) As opposed to one for each character read. --- src/main/java/org/apache/commons/csv/CSVFormat.java | 10 ++++++---- .../apache/commons/csv/ExtendedBufferedReader.java | 13 ------------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/apache/commons/csv/CSVFormat.java b/src/main/java/org/apache/commons/csv/CSVFormat.java index 9ab21d5a..c8e566f9 100644 --- a/src/main/java/org/apache/commons/csv/CSVFormat.java +++ b/src/main/java/org/apache/commons/csv/CSVFormat.java @@ -2191,15 +2191,17 @@ public final class CSVFormat implements Serializable { int pos = 0; @SuppressWarnings("resource") // Temp reader on input reader. final ExtendedBufferedReader bufferedReader = new ExtendedBufferedReader(reader); - final char[] delim = getDelimiterCharArray(); - final int delimLength = delim.length; + final char[] delimArray = getDelimiterCharArray(); + final int delimLength = delimArray.length; final char escape = getEscapeChar(); final StringBuilder builder = new StringBuilder(IOUtils.DEFAULT_BUFFER_SIZE); int c; + final char[] lookAheadBuffer = new char[delimLength - 1]; while (EOF != (c = bufferedReader.read())) { builder.append((char) c); - final boolean isDelimiterStart = isDelimiter((char) c, builder.toString() + new String(bufferedReader.lookAhead(delimLength - 1)), pos, delim, - delimLength); + Arrays.fill(lookAheadBuffer, (char) 0); + final String test = builder.toString() + new String(bufferedReader.lookAhead(lookAheadBuffer)); + final boolean isDelimiterStart = isDelimiter((char) c, test, pos, delimArray, delimLength); final boolean isCr = c == CR; final boolean isLf = c == LF; if (isCr || isLf || c == escape || isDelimiterStart) { diff --git a/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java b/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java index e193c487..7b833ede 100644 --- a/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java +++ b/src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java @@ -139,19 +139,6 @@ final class ExtendedBufferedReader extends BufferedReader { return buf; } - /** - * Returns the next n characters in the current reader without consuming them. The next call to {@link #read()} will still return the next value. This - * doesn't affect line number or last character. - * - * @param n the number characters look ahead. - * @return the next n characters. - * @throws IOException If an I/O error occurs - */ - char[] lookAhead(final int n) throws IOException { - final char[] buf = new char[n]; - return lookAhead(buf); - } - @Override public int read() throws IOException { final int current = super.read();