This is an automated email from the ASF dual-hosted git repository.

chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-mime4j.git

commit 7ae009358ee9c64aacc5e905f9ff63588ab3053d
Author: Benoit TELLIER <[email protected]>
AuthorDate: Tue Dec 1 19:46:06 2026 +0100

    [PERF] TextInputStream: encode the text from an array-backed window
    
    CharBuffer.wrap(CharSequence) is a read-only buffer without an array, so the
    JDK encoders took their char-by-char loop (encodeBufferLoop: a virtual get()
    and String.charAt per char), 19% of MessageWriterBenchmark.writeMessage, and
    missed the ASCII fast path of encodeArrayLoop.
    
    The text is now copied 256 chars at a time into a char[] window
    (String.getChars, charAt for other CharSequences) that the encoder reads. A
    high surrogate left at the end of a window is carried over into the next 
one;
    the end of input is signalled only with the last window. REPLACE on 
malformed
    and unmappable input, the flush of stateful charsets, skip, available and
    mark / reset keep their behaviour, now on the position in the text. A test
    compares the output with String.getBytes across window boundaries.
---
 .../apache/james/mime4j/io/TextInputStream.java    | 84 ++++++++++++++++++----
 .../james/mime4j/io/TextInputStreamTest.java       | 64 +++++++++++++++++
 2 files changed, 136 insertions(+), 12 deletions(-)

diff --git a/core/src/main/java/org/apache/james/mime4j/io/TextInputStream.java 
b/core/src/main/java/org/apache/james/mime4j/io/TextInputStream.java
index c39b8f55..03611731 100644
--- a/core/src/main/java/org/apache/james/mime4j/io/TextInputStream.java
+++ b/core/src/main/java/org/apache/james/mime4j/io/TextInputStream.java
@@ -34,8 +34,20 @@ import java.nio.charset.CodingErrorAction;
  */
 class TextInputStream extends InputStream {
 
+    // chars copied at once from the text into the window: enough to amortize 
an encode call,
+    // small enough not to weigh on the allocation of each body written
+    private static final int WINDOW_SIZE = 256;
+
     private final CharsetEncoder encoder;
+    private final CharSequence text;
+    private final int length;
+    // The encoder reads an array-backed window rather than 
CharBuffer.wrap(text): for a read-only
+    // CharBuffer the JDK encoders take their char-by-char loop, without the 
ASCII fast path.
+    private final char[] window;
+    // the chars of the window not encoded yet
     private final CharBuffer cbuf;
+    // index in text of the first char not copied into the window
+    private int textPos;
     private final ByteBuffer bbuf;
 
     private int mark = -1;
@@ -51,17 +63,65 @@ class TextInputStream extends InputStream {
             .onUnmappableCharacter(CodingErrorAction.REPLACE);
         this.bbuf = ByteBuffer.allocate(bufferSize);
         this.bbuf.flip();
-        this.cbuf = CharBuffer.wrap(s);
+        this.text = s;
+        this.length = s.length();
+        this.window = new char[Math.max(2, Math.min(this.length, 
WINDOW_SIZE))];
+        this.cbuf = CharBuffer.wrap(this.window);
+        this.cbuf.limit(0);
+        this.textPos = 0;
+    }
+
+    // index in text of the first char not encoded yet
+    private int position() {
+        return this.textPos - this.cbuf.remaining();
+    }
+
+    // Moves the chars not encoded yet (a high surrogate waiting for its low 
one) to the start of
+    // the window, and fills the rest from the text
+    private void refillWindow() {
+        int remaining = this.cbuf.remaining();
+        System.arraycopy(this.window, this.cbuf.position(), this.window, 0, 
remaining);
+        int n = Math.min(this.window.length - remaining, this.length - 
this.textPos);
+        if (this.text instanceof String) {
+            ((String) this.text).getChars(this.textPos, this.textPos + n, 
this.window, remaining);
+        } else {
+            for (int i = 0; i < n; i++) {
+                this.window[remaining + i] = this.text.charAt(this.textPos + 
i);
+            }
+        }
+        this.textPos += n;
+        this.cbuf.clear();
+        this.cbuf.limit(remaining + n);
+    }
+
+    // Forgets the window and goes on encoding from the given index of the text
+    private void moveTo(int pos) {
+        this.textPos = pos;
+        this.cbuf.clear();
+        this.cbuf.limit(0);
     }
 
     private void fillBuffer() throws CharacterCodingException {
         this.bbuf.compact();
-        if (!this.encoded) {
-            CoderResult result = this.encoder.encode(this.cbuf, this.bbuf, 
true);
+        while (!this.encoded) {
+            if (!this.cbuf.hasRemaining()) {
+                refillWindow();
+            }
+            boolean endOfInput = this.textPos == this.length;
+            CoderResult result = this.encoder.encode(this.cbuf, this.bbuf, 
endOfInput);
             if (result.isError()) {
                 result.throwException();
             }
-            this.encoded = result.isUnderflow();
+            if (!result.isUnderflow()) {
+                // the byte buffer is full
+                break;
+            }
+            if (endOfInput) {
+                this.encoded = true;
+            } else {
+                // the window is consumed, but for a char the encoder needs 
the next one for
+                refillWindow();
+            }
         }
         if (this.encoded && !this.flushed) {
             CoderResult result = this.encoder.flush(this.bbuf);
@@ -135,29 +195,29 @@ class TextInputStream extends InputStream {
 
     @Override
     public long skip(long n) throws IOException {
-        int skipped = 0;
-        while (n > 0 && this.cbuf.hasRemaining()) {
-            this.cbuf.get();
-            n--;
-            skipped++;
+        if (n <= 0) {
+            return 0;
         }
+        int pos = position();
+        int skipped = (int) Math.min(n, this.length - pos);
+        moveTo(pos + skipped);
         return skipped;
     }
 
     @Override
     public int available() throws IOException {
-        return this.cbuf.remaining();
+        return this.length - position();
     }
 
     @Override
     public void mark(int readlimit) {
-        this.mark = this.cbuf.position();
+        this.mark = position();
     }
 
     @Override
     public void reset() throws IOException {
         if (this.mark != -1) {
-            this.cbuf.position(this.mark);
+            moveTo(this.mark);
             this.mark = -1;
             this.encoder.reset();
             this.encoded = false;
diff --git 
a/core/src/test/java/org/apache/james/mime4j/io/TextInputStreamTest.java 
b/core/src/test/java/org/apache/james/mime4j/io/TextInputStreamTest.java
index 9391182e..9e4f33ad 100644
--- a/core/src/test/java/org/apache/james/mime4j/io/TextInputStreamTest.java
+++ b/core/src/test/java/org/apache/james/mime4j/io/TextInputStreamTest.java
@@ -194,4 +194,68 @@ public class TextInputStreamTest {
         Assert.assertArrayEquals(expected, out.toByteArray());
     }
 
+    // The encoder reads the text through a window of 256 chars: what crosses 
it must not change
+    @Test
+    public void shouldEncodeAsStringGetBytesAcrossWindows() throws Exception {
+        java.util.Random random = new java.util.Random(42);
+        String alphabet = "aZ0 
\u00e9\u20ac\ud83d\ude00\ud83d\ude00\ud800\udc00\u3053";
+        Charset[] charsets = {Charsets.UTF_8, Charsets.ISO_8859_1, 
Charsets.US_ASCII, Charset.forName("UTF-16"),
+            Charset.forName("ISO-2022-JP")};
+        int[] lengths = {0, 1, 255, 256, 257, 511, 1023, 1024, 1025, 3000};
+        for (Charset charset : charsets) {
+            for (int length : lengths) {
+                StringBuilder sb = new StringBuilder(length);
+                for (int i = 0; i < length; i++) {
+                    
sb.append(alphabet.charAt(random.nextInt(alphabet.length())));
+                }
+                String text = sb.toString();
+                byte[] expected = text.getBytes(charset);
+                Assert.assertArrayEquals(charset + " " + length, expected,
+                    drain(new TextInputStream(text, charset, 1024)));
+                Assert.assertArrayEquals(charset + " " + length + " small 
buffer", expected,
+                    drain(new TextInputStream(text, charset, 7)));
+                Assert.assertArrayEquals(charset + " " + length + " 
StringBuilder", expected,
+                    drain(new TextInputStream(new StringBuilder(text), 
charset, 1024)));
+            }
+        }
+    }
+
+    @Test
+    public void shouldEncodeASurrogatePairSplitByTheWindow() throws Exception {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < 255; i++) {
+            sb.append('a');
+        }
+        String text = sb.append("\ud83d\ude00b").toString();
+        Assert.assertArrayEquals(text.getBytes(Charsets.UTF_8), drain(new 
TextInputStream(text, Charsets.UTF_8, 1024)));
+    }
+
+    @Test
+    public void skipAndMarkShouldWorkAcrossWindows() throws Exception {
+        StringBuilder sb = new StringBuilder();
+        for (int i = 0; i < 3000; i++) {
+            sb.append((char) ('a' + i % 26));
+        }
+        String text = sb.toString();
+        InputStream in = new TextInputStream(text, Charsets.US_ASCII, 16);
+        Assert.assertEquals(3000, in.available());
+        Assert.assertEquals(2000, in.skip(2000));
+        Assert.assertEquals(1000, in.available());
+        in.mark(0);
+        Assert.assertEquals(text.substring(2000), new String(drain(in), 
Charsets.US_ASCII));
+        in.reset();
+        Assert.assertEquals(text.substring(2000), new String(drain(in), 
Charsets.US_ASCII));
+        Assert.assertEquals(0, in.skip(10));
+    }
+
+    private static byte[] drain(InputStream in) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        byte[] buf = new byte[100];
+        int n;
+        while ((n = in.read(buf)) != -1) {
+            out.write(buf, 0, n);
+        }
+        return out.toByteArray();
+    }
+
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to