ppkarwasz commented on code in PR #776:
URL: https://github.com/apache/commons-io/pull/776#discussion_r2325255942
##########
src/main/java/org/apache/commons/io/IOUtils.java:
##########
@@ -2697,6 +2724,62 @@ public static byte[] toByteArray(final InputStream
input, final long size) throw
return toByteArray(input, (int) size);
}
+ /**
+ * Reads exactly {@code size} bytes from the given {@link InputStream}
into a new {@code byte[]}.
+ *
+ * <p>
+ * This variant validates that the stream actually contains {@code size}
bytes.
+ * It is suitable for untrusted input because it prevents oversized
allocations when the provided {@code size}
+ * is corrupted or malicious.
+ * </p>
+ *
+ * <ul>
+ * <li>If {@code size <= bufferSize}, the array is allocated directly
and filled in a single pass.</li>
+ * <li>
+ * If {@code size > bufferSize}, the stream is read incrementally
using a buffer of length {@code bufferSize}.
+ * This avoids allocating an excessively large array up front,
+ * but may temporarily double memory usage due to buffering.
+ * </li>
+ * </ul>
+ *
+ * @param input the {@link InputStream} to read; must not be {@code
null}.
+ * @param size the exact number of bytes to read; must be {@code >=
0}.
+ * The actual bytes read are validated to equal {@code
size}.
+ * @param bufferSize the buffer size for incremental reading; must be
{@code > 0}.
+ * @return a new byte array of length {@code size}.
+ * @throws IllegalArgumentException if {@code size} is negative or {@code
bufferSize <= 0}.
+ * @throws EOFException if the stream ends before {@code size}
bytes are read.
+ * @throws IOException if an I/O error occurs while reading.
+ * @throws NullPointerException if {@code input} is {@code null}.
+ * @since 2.21.0
+ */
+ public static byte[] toByteArray(final InputStream input, final int size,
final int bufferSize) throws IOException {
+ Objects.requireNonNull(input, "input");
+ if (size < 0) {
Review Comment:
Fixed in
https://github.com/apache/commons-io/pull/776/commits/fe39b777c447f2eeb185ae2520ca6b547d84e719
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]