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 e6f3b149623e84bfcca9f957e0885f0052125bc7
Author: Benoit TELLIER <[email protected]>
AuthorDate: Tue Dec 1 21:05:59 2026 +0100

    [FIX] TextInputStream: skip, available and mark / reset count bytes, not 
chars
    
    They worked on the position of the encoder in the text, which runs ahead of
    the reader by the bytes encoded but not read yet, and counted chars where
    InputStream counts bytes:
    - skip(n) dropped n chars after the encoded bytes, which were still read,
      and returned a char count ("€abc": skip(1) skipped 3 bytes);
    - available() ignored the encoded bytes not read yet;
    - mark() after a read marked the end of what was encoded, and reset() then
      served the bytes not read yet before the text again ("abcdef": mark, read
      3, reset gave "defabcdef").
    
    skip now discards bytes: those not read yet, then those of the chars after
    them. available is the encoded bytes not read yet plus one per char left,
    never more than can be read. mark records the count of bytes read or
    skipped; reset encodes the text again from its start with a fresh encoder
    and skips that many bytes, which gives the same bytes for a stateful charset
    such as ISO-2022-JP.
---
 .../apache/james/mime4j/io/TextInputStream.java    | 54 ++++++++++++---
 .../james/mime4j/io/TextInputStreamTest.java       | 78 ++++++++++++++++++++++
 2 files changed, 123 insertions(+), 9 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 8bcc770f..b0ae22da 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
@@ -51,7 +51,10 @@ class TextInputStream extends InputStream {
     // grown when it cannot hold the bytes of a single char, or the end of a 
stateful encoding
     private ByteBuffer bbuf;
 
-    private int mark = -1;
+    // bytes read or skipped since the start of the text
+    private long bytePos;
+    // bytePos at mark(), -1 when none
+    private long mark = -1;
     // encode(..., true) consumed all the input
     private boolean encoded;
     // flush wrote the final bytes of a stateful encoding, such as the ESC ( B 
of ISO-2022-JP
@@ -170,6 +173,7 @@ class TextInputStream extends InputStream {
             if (this.bbuf.hasRemaining()) {
                 int chunk = Math.min(this.bbuf.remaining(), len);
                 this.bbuf.get(b, off, chunk);
+                this.bytePos += chunk;
                 off += chunk;
                 len -= chunk;
                 bytesRead += chunk;
@@ -195,6 +199,7 @@ class TextInputStream extends InputStream {
     public int read() throws IOException {
         for (;;) {
             if (this.bbuf.hasRemaining()) {
+                this.bytePos++;
                 return this.bbuf.get() & 0xFF;
             } else {
                 fillBuffer();
@@ -212,33 +217,64 @@ class TextInputStream extends InputStream {
 
     @Override
     public long skip(long n) throws IOException {
-        if (n <= 0) {
-            return 0;
+        return discard(n);
+    }
+
+    // Skips up to n bytes: the encoded bytes not read yet, then the bytes of 
the chars after them
+    private long discard(long n) throws IOException {
+        long skipped = 0;
+        while (skipped < n) {
+            if (this.bbuf.hasRemaining()) {
+                int chunk = (int) Math.min(this.bbuf.remaining(), n - skipped);
+                this.bbuf.position(this.bbuf.position() + chunk);
+                this.bytePos += chunk;
+                skipped += chunk;
+            } else {
+                fillBuffer();
+                if (atEnd()) {
+                    break;
+                }
+            }
         }
-        int pos = position();
-        int skipped = (int) Math.min(n, this.length - pos);
-        moveTo(pos + skipped);
         return skipped;
     }
 
+    /**
+     * The encoded bytes not read yet, plus one per char not encoded yet: a 
char encodes to one
+     * byte at least, so this does not exceed what can be read.
+     */
     @Override
     public int available() throws IOException {
-        return this.length - position();
+        long available = (long) this.bbuf.remaining() + (this.length - 
position());
+        return (int) Math.min(Integer.MAX_VALUE, available);
     }
 
+    /**
+     * Marks the byte about to be read. The bytes are not kept: {@link 
#reset()} encodes the
+     * text again, so readlimit does not apply.
+     */
     @Override
     public void mark(int readlimit) {
-        this.mark = position();
+        this.mark = this.bytePos;
     }
 
+    /**
+     * Encodes the text again from its start and skips the bytes before the 
mark: the encoding
+     * restarts where a stateful charset is in its initial state, and gives 
the same bytes.
+     */
     @Override
     public void reset() throws IOException {
         if (this.mark != -1) {
-            moveTo(this.mark);
+            long target = this.mark;
             this.mark = -1;
+            moveTo(0);
             this.encoder.reset();
             this.encoded = false;
             this.flushed = false;
+            this.bbuf.clear();
+            this.bbuf.flip();
+            this.bytePos = 0;
+            discard(target);
         }
     }
 
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 0dc50a1b..fa1a1ba9 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
@@ -267,6 +267,84 @@ public class TextInputStreamTest {
         Assert.assertArrayEquals(kanji.getBytes(iso2022jp), drain(new 
TextInputStream(kanji, iso2022jp, 1)));
     }
 
+    // skip counted chars not encoded yet: the encoded bytes were still read, 
the chars after
+    // them dropped, and a multi-byte char counted as one
+    @Test
+    public void skipShouldSkipBytes() throws Exception {
+        InputStream in = new TextInputStream("\u20acabc", Charsets.UTF_8, 
1024);
+        Assert.assertEquals(1, in.skip(1));
+        Assert.assertEquals(0x82, in.read());
+        Assert.assertEquals(2, in.skip(2));
+        Assert.assertEquals('b', in.read());
+        Assert.assertEquals(1, in.skip(10));
+        Assert.assertEquals(-1, in.read());
+        Assert.assertEquals(0, in.skip(10));
+    }
+
+    @Test
+    public void skipShouldNotLoseTheBytesAlreadyEncoded() 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, 1024);
+        Assert.assertEquals(text.charAt(0), in.read());
+        Assert.assertEquals(10, in.skip(10));
+        Assert.assertEquals(text.substring(11), new String(drain(in), 
Charsets.US_ASCII));
+    }
+
+    @Test
+    public void availableShouldNotExceedTheBytesLeft() throws Exception {
+        String text = "\u20acabc";
+        InputStream in = new TextInputStream(text, Charsets.UTF_8, 1024);
+        int left = text.getBytes(Charsets.UTF_8).length;
+        while (true) {
+            int available = in.available();
+            Assert.assertTrue(available + " > " + left, available <= left);
+            if (in.read() == -1) {
+                break;
+            }
+            left--;
+        }
+        Assert.assertEquals(0, in.available());
+    }
+
+    // mark() recorded the position of the encoder, ahead of the reader by the 
bytes encoded but
+    // not read: reset() replayed them before the text again
+    @Test
+    public void resetShouldReturnToTheMarkedByte() throws Exception {
+        InputStream in = new TextInputStream("abcdef", Charsets.US_ASCII, 
1024);
+        in.mark(0);
+        byte[] buf = new byte[3];
+        Assert.assertEquals(3, in.read(buf));
+        in.reset();
+        Assert.assertEquals("abcdef", new String(drain(in), 
Charsets.US_ASCII));
+
+        in = new TextInputStream("abcdef", Charsets.US_ASCII, 1024);
+        Assert.assertEquals('a', in.read());
+        in.mark(0);
+        Assert.assertEquals('b', in.read());
+        in.reset();
+        Assert.assertEquals("bcdef", new String(drain(in), Charsets.US_ASCII));
+    }
+
+    @Test
+    public void resetShouldReturnToTheMarkedByteOfAStatefulCharset() throws 
Exception {
+        Charset iso2022jp = Charset.forName("ISO-2022-JP");
+        String text = "a\u3053\u3093b\u3053";
+        byte[] expected = text.getBytes(iso2022jp);
+        for (int markAt = 0; markAt <= expected.length; markAt++) {
+            InputStream in = new TextInputStream(text, iso2022jp, 4);
+            Assert.assertEquals(markAt, in.skip(markAt));
+            in.mark(0);
+            drain(in);
+            in.reset();
+            Assert.assertArrayEquals("mark at " + markAt,
+                java.util.Arrays.copyOfRange(expected, markAt, 
expected.length), drain(in));
+        }
+    }
+
     private static byte[] drain(InputStream in) throws IOException {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         byte[] buf = new byte[100];


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

Reply via email to