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 804b904c41099865db57da4746bfae723336de54
Author: Benoit TELLIER <[email protected]>
AuthorDate: Tue Dec 1 19:47:26 2026 +0100

    [PERF] RawFieldParser.copyRun: cache the delimiter masks and append an 
ASCII run at once
    
    copyRun rebuilt its two delimiter masks with BitSet.nextSetBit on every run,
    one call per word (5% of parseAddressList, 9.5% of
    parseUnclosedDomainLiterals), although the sets are almost always the same
    static final ones of LenientAddressParser and RawFieldParser. It then
    appended the run char by char, a capacity and coder check each (about 8%).
    
    The masks are now kept per parser in a small cache of immutable entries,
    found by identity and checked with BitSet#equals against a snapshot, so that
    a set changed by its caller is not served stale masks; the race between
    threads only computes masks again. An ASCII run without line break read from
    a ByteArrayBuffer is appended as one ISO-8859-1 String when it holds 16 
chars
    or more: for a shorter run the String costs more than the loop (10 000
    one-char runs of unclosed domain literals allocated 5 times as much). 
Non-ASCII
    delimiters still go through BitSet#get, CR and LF are still deleted.
---
 .../apache/james/mime4j/stream/RawFieldParser.java | 116 ++++++++++++++++++---
 .../james/mime4j/stream/RawFieldParserTest.java    |  44 ++++++++
 2 files changed, 145 insertions(+), 15 deletions(-)

diff --git 
a/core/src/main/java/org/apache/james/mime4j/stream/RawFieldParser.java 
b/core/src/main/java/org/apache/james/mime4j/stream/RawFieldParser.java
index 6c9c1a0b..8aa80a8d 100644
--- a/core/src/main/java/org/apache/james/mime4j/stream/RawFieldParser.java
+++ b/core/src/main/java/org/apache/james/mime4j/stream/RawFieldParser.java
@@ -405,29 +405,103 @@ public class RawFieldParser {
     private static final long QUOTE = 1L << '\"';
 
     /**
-     * Copies the run of bytes from the cursor to the first whitespace, '(', 
'"' when
-     * <code>stopAtQuote</code>, or delimiter. CR and LF are deleted, as by 
MimeUtil#unfold: the
-     * word goes on. A run holding a non-ASCII byte is decoded as UTF-8.
-     * <p>
-     * The run is found first, then appended at once: the stop test is two bit 
masks for ASCII.
+     * The delimiters of a BitSet as bit masks: ASCII below 64, ASCII from 64, 
and whether a
+     * delimiter is not ASCII. Immutable: shared between threads through 
{@link #stopMasks}.
      */
-    private void copyRun(final ByteSequence buf, final ParserCursor cursor, 
final BitSet delimiters,
-            final StringBuilder dst, final boolean stopAtQuote) {
-        long stopLow = WSP_OR_COMMENT | (stopAtQuote ? QUOTE : 0L);
-        long stopHigh = 0L;
-        boolean nonAsciiDelimiters = false;
-        if (delimiters != null) {
+    private static final class StopMasks {
+        private static final StopMasks NONE = new StopMasks(null, null, 0L, 
0L, false);
+
+        // the BitSet the masks were computed for, compared by identity
+        private final BitSet source;
+        // its content then, should a caller have changed it since
+        private final BitSet snapshot;
+        private final long low;
+        private final long high;
+        private final boolean nonAscii;
+
+        private StopMasks(BitSet source, BitSet snapshot, long low, long high, 
boolean nonAscii) {
+            this.source = source;
+            this.snapshot = snapshot;
+            this.low = low;
+            this.high = high;
+            this.nonAscii = nonAscii;
+        }
+
+        static StopMasks of(BitSet delimiters) {
+            long low = 0L;
+            long high = 0L;
+            boolean nonAscii = false;
             for (int d = delimiters.nextSetBit(0); d >= 0; d = 
delimiters.nextSetBit(d + 1)) {
                 if (d < 64) {
-                    stopLow |= 1L << d;
+                    low |= 1L << d;
                 } else if (d < 128) {
-                    stopHigh |= 1L << (d - 64);
+                    high |= 1L << (d - 64);
                 } else {
-                    nonAsciiDelimiters = true;
+                    nonAscii = true;
                     break;
                 }
             }
+            // not clone(): it trims the words of a non-sticky source, a write 
to a set shared
+            // between threads. or() only reads it.
+            BitSet snapshot = new BitSet();
+            snapshot.or(delimiters);
+            return new StopMasks(delimiters, snapshot, low, high, nonAscii);
+        }
+
+        boolean matches(BitSet delimiters) {
+            // BitSet#equals compares a word or two for ASCII sets: cheaper 
than rebuilding the masks
+            return source == delimiters && snapshot.equals(delimiters);
+        }
+    }
+
+    private static final int STOP_MASKS_CACHE_SIZE = 16;
+    // the shortest ASCII run appended through a String rather than char by 
char
+    private static final int BULK_APPEND_MIN = 16;
+    // The masks of the last delimiter sets: a parser runs one copyRun per 
word with the same few
+    // sets, mostly static final ones (LenientAddressParser has 10), plus the 
union built once by
+    // each parseMailboxes / parseAddress entry: room for the static sets and 
a few of those.
+    // Racy on purpose: entries are immutable, a lost update only computes the 
masks again. The
+    // delimiter sets are only read.
+    private final StopMasks[] stopMasks = new StopMasks[STOP_MASKS_CACHE_SIZE];
+    private int nextStopMasks = 0;
+    // the entry found by the last lookup, checked first
+    private StopMasks lastStopMasks = StopMasks.NONE;
+
+    private StopMasks stopMasks(final BitSet delimiters) {
+        if (delimiters == null) {
+            return StopMasks.NONE;
+        }
+        // the words of a value mostly run to the same delimiters as the word 
before
+        final StopMasks last = this.lastStopMasks;
+        if (last.matches(delimiters)) {
+            return last;
+        }
+        final StopMasks[] cache = this.stopMasks;
+        for (StopMasks masks : cache) {
+            if (masks != null && masks.matches(delimiters)) {
+                this.lastStopMasks = masks;
+                return masks;
+            }
         }
+        StopMasks masks = StopMasks.of(delimiters);
+        cache[nextStopMasks++ & (STOP_MASKS_CACHE_SIZE - 1)] = masks;
+        this.lastStopMasks = masks;
+        return masks;
+    }
+
+    /**
+     * Copies the run of bytes from the cursor to the first whitespace, '(', 
'"' when
+     * <code>stopAtQuote</code>, or delimiter. CR and LF are deleted, as by 
MimeUtil#unfold: the
+     * word goes on. A run holding a non-ASCII byte is decoded as UTF-8.
+     * <p>
+     * The run is found first, then appended at once: the stop test is two bit 
masks for ASCII.
+     */
+    private void copyRun(final ByteSequence buf, final ParserCursor cursor, 
final BitSet delimiters,
+            final StringBuilder dst, final boolean stopAtQuote) {
+        final StopMasks masks = stopMasks(delimiters);
+        final long stopLow = masks.low | WSP_OR_COMMENT | (stopAtQuote ? QUOTE 
: 0L);
+        final long stopHigh = masks.high;
+        final boolean nonAsciiDelimiters = masks.nonAscii;
         final int indexFrom = cursor.getPos();
         final int indexTo = cursor.getUpperBound();
         boolean nonAscii = false;
@@ -467,13 +541,25 @@ public class RawFieldParser {
             dst.append(ContentUtil.decode(StandardCharsets.UTF_8, dstRaw));
             return;
         }
-        dst.ensureCapacity(dst.length() + (end - indexFrom));
         if (!lineBreak) {
+            if (end == indexFrom) {
+                return;
+            }
+            if (end - indexFrom >= BULK_APPEND_MIN && buf instanceof 
ByteArrayBuffer) {
+                // a long ASCII run appended in one copy rather than a 
capacity check per char. Not
+                // a short one: the String would cost more than the loop (10 
000 one-char runs of
+                // unclosed domain literals allocated 5 times as much)
+                dst.append(new String(((ByteArrayBuffer) buf).buffer(), 
indexFrom, end - indexFrom,
+                    StandardCharsets.ISO_8859_1));
+                return;
+            }
+            dst.ensureCapacity(dst.length() + (end - indexFrom));
             for (int j = indexFrom; j < end; j++) {
                 dst.append((char) (buf.byteAt(j) & 0xff));
             }
             return;
         }
+        dst.ensureCapacity(dst.length() + (end - indexFrom));
         for (int j = indexFrom; j < end; j++) {
             char c = (char) (buf.byteAt(j) & 0xff);
             if (!isLineBreak(c)) {
diff --git 
a/core/src/test/java/org/apache/james/mime4j/stream/RawFieldParserTest.java 
b/core/src/test/java/org/apache/james/mime4j/stream/RawFieldParserTest.java
index e4239046..c79e9e76 100644
--- a/core/src/test/java/org/apache/james/mime4j/stream/RawFieldParserTest.java
+++ b/core/src/test/java/org/apache/james/mime4j/stream/RawFieldParserTest.java
@@ -592,4 +592,48 @@ public class RawFieldParserTest {
         // other parameters keep the backslash before an ordinary character, 
as before
         org.junit.Assert.assertEquals("a\\bc", 
body.getParams().get(1).getValue());
     }
+    // The masks of a delimiter set are cached: a set changed by its caller 
must not be stale
+    @Test
+    public void copyContentShouldSeeADelimiterSetChangedBetweenCalls() throws 
Exception {
+        java.util.BitSet delimiters = RawFieldParser.INIT_BITSET(':');
+        ByteSequence raw = ContentUtil.encode("ab;cd:ef");
+
+        StringBuilder dst = new StringBuilder();
+        parser.copyContent(raw, new ParserCursor(0, raw.length()), delimiters, 
dst);
+        Assert.assertEquals("ab;cd", dst.toString());
+
+        delimiters.set(';');
+        dst = new StringBuilder();
+        parser.copyContent(raw, new ParserCursor(0, raw.length()), delimiters, 
dst);
+        Assert.assertEquals("ab", dst.toString());
+
+        delimiters.clear();
+        dst = new StringBuilder();
+        parser.copyContent(raw, new ParserCursor(0, raw.length()), delimiters, 
dst);
+        Assert.assertEquals("ab;cd:ef", dst.toString());
+    }
+
+    @Test
+    public void copyContentShouldHandleMoreDelimiterSetsThanTheCacheHolds() 
throws Exception {
+        ByteSequence raw = ContentUtil.encode("abcdefghijklmnop");
+        for (int round = 0; round < 3; round++) {
+            for (char c = 'b'; c <= 'p'; c++) {
+                StringBuilder dst = new StringBuilder();
+                parser.copyContent(raw, new ParserCursor(0, raw.length()), 
RawFieldParser.INIT_BITSET(c), dst);
+                Assert.assertEquals("abcdefghijklmnop".substring(0, c - 'a'), 
dst.toString());
+            }
+        }
+    }
+
+    @Test
+    public void copyContentShouldCopyALongRunAtOnce() throws Exception {
+        String word = "abcdefghijklmnopqrstuvwxyz0123456789.-_";
+        ByteSequence raw = ContentUtil.encode(word + ":rest");
+        StringBuilder dst = new StringBuilder("x");
+        ParserCursor cursor = new ParserCursor(0, raw.length());
+        parser.copyContent(raw, cursor, RawFieldParser.INIT_BITSET(':'), dst);
+        Assert.assertEquals("x" + word, dst.toString());
+        Assert.assertEquals(word.length(), cursor.getPos());
+    }
+
 }


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

Reply via email to