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

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-codec.git

commit b87f612e8af570ce7c45237797c8526a8b3ba0d4
Author: Gary Gregory <[email protected]>
AuthorDate: Sat Nov 21 15:29:06 2026 -0500

    Report buffered output as available after codec EOF
    
    Return zero from BaseNCodecInputStream.available() only when the codec
    has reached EOF and its output buffer is empty. Preserve the existing
    0-or-1 availability contract.
    
    Add regression tests across all five Base-N input streams for reads,
    skips, buffer boundaries, strict validation, and open pipes.
    
    Update Javadoc.
---
 src/changes/changes.xml                            |   1 +
 .../codec/binary/BaseNCodecInputStream.java        |  14 +-
 .../codec/binary/BaseNCodecInputStreamTest.java    | 172 ++++++++++++++++++++-
 3 files changed, 179 insertions(+), 8 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 5e0ae70a..1e0521a3 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -67,6 +67,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="simpleqt, Gary Gregory, Piotr 
P. Karwasz">GitIdentifiers: record files as regular without POSIX permissions 
(#458).</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Stop 
BaseNCodecInputStream from reading the underlying stream after codec EOF, 
preventing unnecessary reads and blocking after padding in lenient Base32 and 
Base64 decoding.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Compute Digest 
ALL and * standard-input digests in a single pass with bounded buffering, 
removing the mark/reset input-size limit.</action>
+      <action type="fix" dev="ggregory" due-to="Gary Gregory">Keep 
BaseNCodecInputStream.available() positive after codec EOF while output remains 
buffered.</action>
       <!-- ADD -->
       <!-- UPDATE -->
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-parent from 105 to 107.</action>
diff --git 
a/src/main/java/org/apache/commons/codec/binary/BaseNCodecInputStream.java 
b/src/main/java/org/apache/commons/codec/binary/BaseNCodecInputStream.java
index e2a90781..aed1734c 100644
--- a/src/main/java/org/apache/commons/codec/binary/BaseNCodecInputStream.java
+++ b/src/main/java/org/apache/commons/codec/binary/BaseNCodecInputStream.java
@@ -131,17 +131,19 @@ public class BaseNCodecInputStream<C extends BaseNCodec, 
T extends BaseNCodecInp
     /**
      * {@inheritDoc}
      *
-     * @return {@code 0} if the {@link InputStream} has reached {@code EOF}, 
{@code 1} otherwise.
+     * <p>
+     * Returns an availability indicator rather than the number of buffered 
bytes. Buffered output remains available after the codec reaches EOF until it
+     * has been consumed. This method does not read from or query the 
underlying stream.
+     * </p>
+     *
+     * @return {@code 0} if the codec has reached EOF and no buffered output 
remains, {@code 1} otherwise.
      * @throws IOException Thrown if an I/O error occurs.
      * @since 1.7
      */
     @Override
     public int available() throws IOException {
-        // Note: The logic is similar to the InflaterInputStream:
-        // as long as we have not reached EOF, indicate that there is more
-        // data available. As we do not know for sure how much data is left,
-        // just return 1 as a safe guess.
-        return context.eof ? 0 : 1;
+        // Report EOF only after all buffered output has been consumed.
+        return context.eof && !baseNCodec.hasData(context) ? 0 : 1;
     }
 
     /**
diff --git 
a/src/test/java/org/apache/commons/codec/binary/BaseNCodecInputStreamTest.java 
b/src/test/java/org/apache/commons/codec/binary/BaseNCodecInputStreamTest.java
index dbcd6674..e6adceb0 100644
--- 
a/src/test/java/org/apache/commons/codec/binary/BaseNCodecInputStreamTest.java
+++ 
b/src/test/java/org/apache/commons/codec/binary/BaseNCodecInputStreamTest.java
@@ -42,7 +42,7 @@ import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.MethodSource;
 
 /**
- * Tests EOF handling shared by all Base-N input streams.
+ * Tests EOF handling and availability shared by all Base-N input streams.
  */
 class BaseNCodecInputStreamTest {
 
@@ -73,6 +73,11 @@ class BaseNCodecInputStreamTest {
             this.allowEof = allowEof;
         }
 
+        @Override
+        public int available() {
+            throw new AssertionError("The codec stream must not query the 
source's availability");
+        }
+
         @Override
         public void close() {
             closed = true;
@@ -106,11 +111,53 @@ class BaseNCodecInputStreamTest {
 
     private static final int[] READ_SIZES = { -64, -3, 0, 1, 3, 64 };
 
+    private static void assertAvailable(final int expected, final InputStream 
stream, final EofTrackingInputStream source) throws IOException {
+        final int calls = source.readCalls;
+        assertEquals(expected, stream.available());
+        assertEquals(expected, stream.available(), "Repeated availability 
checks must not change stream state");
+        assertEquals(calls, source.readCalls, "Availability checks must not 
read from the source");
+        assertFalse(source.closed, "Availability checks must not close the 
source");
+    }
+
+    private static void assertAvailableWhileReading(final byte[] expected, 
final InputStream stream, final EofTrackingInputStream source,
+            final int readSize) throws IOException {
+        assertAvailable(1, stream, source);
+        int position = 0;
+        while (position < expected.length) {
+            assertAvailable(1, stream, source);
+            assertEquals(0, stream.read(new byte[0]));
+            assertEquals(0, stream.skip(0));
+            assertAvailable(1, stream, source);
+            if (readSize == 0) {
+                assertEquals(expected[position++] & 0xff, stream.read());
+            } else {
+                final int capacity = Math.abs(readSize);
+                final int offset = readSize < 0 ? 0 : 1;
+                final byte[] buffer = new byte[capacity + 2 * offset];
+                Arrays.fill(buffer, (byte) 0x5a);
+                final int count = readSize < 0 ? stream.read(buffer) : 
stream.read(buffer, offset, capacity);
+                assertEquals(Math.min(capacity, expected.length - position), 
count);
+                assertArrayEquals(Arrays.copyOfRange(expected, position, 
position + count), Arrays.copyOfRange(buffer, offset, offset + count));
+                if (offset != 0) {
+                    assertEquals(0x5a, buffer[0]);
+                    assertEquals(0x5a, buffer[buffer.length - 1]);
+                }
+                position += count;
+            }
+        }
+        if (source.eofReturns != 0) {
+            assertAvailable(0, stream, source);
+        }
+        assertEquals(-1, stream.read());
+        assertFinished(stream, source);
+    }
+
     /**
      * EOF must be stable for all read and skip overloads, while zero-length 
reads and argument validation retain their normal behavior.
      */
     private static void assertFinished(final InputStream stream, final 
EofTrackingInputStream source) throws IOException {
         final int calls = source.readCalls;
+        assertAvailable(0, stream, source);
         assertEquals(-1, stream.read());
         assertEquals(-1, stream.read());
         assertEquals(-1, stream.read(new byte[4]));
@@ -122,6 +169,7 @@ class BaseNCodecInputStreamTest {
         assertThrows(NullPointerException.class, () -> stream.read(null, 0, 
0));
         assertThrows(IndexOutOfBoundsException.class, () -> stream.read(new 
byte[1], 2, 0));
         assertThrows(IllegalArgumentException.class, () -> stream.skip(-1));
+        assertAvailable(0, stream, source);
         assertEquals(calls, source.readCalls, "EOF operations must not read 
from the source");
         assertFalse(source.closed, "Reaching EOF must not close the source");
     }
@@ -147,6 +195,18 @@ class BaseNCodecInputStreamTest {
         return arguments.stream();
     }
 
+    static Stream<Arguments> largeCodecs() {
+        return codecs().map(arguments -> {
+            final BaseNCodec codec = (BaseNCodec) arguments.get()[1];
+            if (codec instanceof Base58) {
+                // Raise the Base58 input limits so these tests can cross the 
stream's 4096- and 8192-byte buffer boundaries.
+                return Arguments.of(arguments.get()[0], 
Base58.builder().setMaxEncodeLength(16384).setMaxDecodeLength(16384)
+                        .setDecodingPolicy(codec.isStrictDecoding() ? 
CodecPolicy.STRICT : CodecPolicy.LENIENT).get());
+            }
+            return arguments;
+        });
+    }
+
     private static InputStream newStream(final InputStream source, final 
BaseNCodec codec, final boolean encode) {
         if (codec instanceof Base16) {
             return 
Base16InputStream.builder().setInputStream(source).setBaseNCodec((Base16) 
codec).setEncode(encode).get();
@@ -227,6 +287,110 @@ class BaseNCodecInputStreamTest {
         });
     }
 
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("largeCodecs")
+    void testAvailableAcrossInternalBufferBoundaries(final String name, final 
BaseNCodec codec) throws IOException {
+        for (final int length : new int[] { 4095, 4096, 4097, 8191, 8192, 8193 
}) {
+            final byte[] decoded = payload(length);
+            final byte[] encoded = codec.encode(decoded);
+            for (final boolean encode : new boolean[] { false, true }) {
+                for (final int chunkSize : new int[] { 257, 8192 }) {
+                    final EofTrackingInputStream source = new 
EofTrackingInputStream(encode ? decoded : encoded, chunkSize, true);
+                    try (InputStream stream = newStream(source, codec, 
encode)) {
+                        assertAvailableWhileReading(encode ? encoded : 
decoded, stream, source, 333);
+                    }
+                }
+            }
+        }
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("strictStreamingCodecs")
+    void testAvailableDoesNotHidePendingStrictValidation(final String name, 
final BaseNCodec codec) throws IOException {
+        final byte[] decoded = payload(15);
+        final byte[] encoded = codec.encode(decoded);
+        final EofTrackingInputStream source = new 
EofTrackingInputStream(encoded, encoded.length, false);
+        try (InputStream stream = newStream(source, codec, false)) {
+            final byte[] output = new byte[decoded.length];
+            assertEquals(output.length, stream.read(output));
+            assertArrayEquals(decoded, output);
+            assertAvailable(1, stream, source);
+            assertEquals(0, source.eofReturns);
+            assertSame(source.unexpectedRead, assertThrows(IOException.class, 
stream::read));
+        }
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("paddedCodecs")
+    void testAvailableDrainsPaddingOutputWithoutReadingTheNextChunk(final 
String name, final BaseNCodec codec) throws IOException {
+        final byte[] decoded = payload(7);
+        final byte[] encoded = codec.encode(decoded);
+        final byte[] input = Arrays.copyOf(encoded, encoded.length + 1);
+        input[encoded.length] = '!';
+        final EofTrackingInputStream source = new 
EofTrackingInputStream(input, encoded.length, false);
+        try (InputStream stream = newStream(source, codec, false)) {
+            for (int i = 0; i < decoded.length; i++) {
+                assertAvailable(1, stream, source);
+                if (i % 2 == 0) {
+                    assertEquals(decoded[i] & 0xff, stream.read());
+                } else {
+                    assertEquals(1, stream.skip(1));
+                }
+            }
+            assertAvailable(0, stream, source);
+            assertFinished(stream, source);
+            assertEquals(encoded.length, source.position);
+            assertEquals(0, source.eofReturns);
+            assertEquals('!', source.read());
+        }
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("codecs")
+    void testAvailableWhileReading(final String name, final BaseNCodec codec) 
throws IOException {
+        for (final boolean encode : new boolean[] { false, true }) {
+            for (int length = 0; length <= 11; length++) {
+                final byte[] decoded = payload(length);
+                final byte[] encoded = codec.encode(decoded);
+                for (final int chunkSize : new int[] { 1, 7, 8192 }) {
+                    for (final int readSize : READ_SIZES) {
+                        final EofTrackingInputStream source = new 
EofTrackingInputStream(encode ? decoded : encoded, chunkSize, true);
+                        try (InputStream stream = newStream(source, codec, 
encode)) {
+                            assertAvailableWhileReading(encode ? encoded : 
decoded, stream, source, readSize);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    @ParameterizedTest(name = "{0}")
+    @MethodSource("codecs")
+    void testAvailableWhileSkipping(final String name, final BaseNCodec codec) 
throws IOException {
+        for (final boolean encode : new boolean[] { false, true }) {
+            for (int length = 0; length <= 11; length++) {
+                final byte[] decoded = payload(length);
+                final byte[] encoded = codec.encode(decoded);
+                final byte[] expected = encode ? encoded : decoded;
+                for (final int chunkSize : new int[] { 1, 8192 }) {
+                    final EofTrackingInputStream source = new 
EofTrackingInputStream(encode ? decoded : encoded, chunkSize, true);
+                    try (InputStream stream = newStream(source, codec, 
encode)) {
+                        assertAvailable(1, stream, source);
+                        for (int i = 0; i < expected.length; i++) {
+                            assertAvailable(1, stream, source);
+                            assertEquals(1, stream.skip(1));
+                        }
+                        if (source.eofReturns != 0) {
+                            assertAvailable(0, stream, source);
+                        }
+                        assertEquals(0, stream.skip(Long.MAX_VALUE));
+                        assertFinished(stream, source);
+                    }
+                }
+            }
+        }
+    }
+
     @ParameterizedTest(name = "{0}")
     @MethodSource("paddedCodecs")
     void testLenientPaddingCanFinishWithoutOutput(final String name, final 
BaseNCodec codec) throws IOException {
@@ -268,7 +432,11 @@ class BaseNCodecInputStreamTest {
             writer.flush();
             // Keep the writer open until the decoder has returned all its 
output and EOF.
             assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
-                assertArrayEquals(decoded, readAll(stream, 64));
+                for (final byte value : decoded) {
+                    assertEquals(1, stream.available());
+                    assertEquals(value & 0xff, stream.read());
+                }
+                assertEquals(0, stream.available());
                 assertEquals(-1, stream.read());
             });
         }

Reply via email to