From 9d3de3572aa8c2dea3b36f2f58fd9153d7413c32 Mon Sep 17 00:00:00 2001 From: Santiago Pericas-Geertsen Date: Mon, 22 Apr 2024 16:57:06 -0400 Subject: [PATCH] Properly handles an empty input stream by keeping the internal state of a GrowingBufferData consistent. (#8694) Signed-off-by: Santiago Pericas-Geertsen --- .../common/buffers/GrowingBufferData.java | 6 ++++-- .../helidon/common/buffers/BufferDataTest.java | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/common/buffers/src/main/java/io/helidon/common/buffers/GrowingBufferData.java b/common/buffers/src/main/java/io/helidon/common/buffers/GrowingBufferData.java index b5b42b4bb39..cea031919a6 100644 --- a/common/buffers/src/main/java/io/helidon/common/buffers/GrowingBufferData.java +++ b/common/buffers/src/main/java/io/helidon/common/buffers/GrowingBufferData.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 2024 Oracle and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,9 @@ public void writeTo(OutputStream out) { public int readFrom(InputStream in) { try { int read = in.read(bytes, writePosition, bytes.length - writePosition); - writePosition += read; + if (read > 0) { + writePosition += read; + } return read; } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/common/buffers/src/test/java/io/helidon/common/buffers/BufferDataTest.java b/common/buffers/src/test/java/io/helidon/common/buffers/BufferDataTest.java index a4eb3c0e97b..ddf77fd04c2 100644 --- a/common/buffers/src/test/java/io/helidon/common/buffers/BufferDataTest.java +++ b/common/buffers/src/test/java/io/helidon/common/buffers/BufferDataTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 2024 Oracle and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package io.helidon.common.buffers; +import java.io.InputStream; import java.util.HexFormat; import java.util.stream.Stream; @@ -285,6 +286,20 @@ void testHexOutput(TestContext context) { assertThat(bd.debugDataHex(true), is(expected)); } + @ParameterizedTest + @MethodSource("initParams") + void emptyInputStream(TestContext context) { + BufferData b = context.bufferData(); + assertThat(b.available(), is(0)); + b.readFrom(new InputStream() { + @Override + public int read() { + return -1; // no data + } + }); + assertThat(b.available(), is(0)); + } + BufferData dataFromHex(String hexEncoded) { byte[] bytes = HexFormat.of().parseHex(hexEncoded.replace(" ", "")); return BufferData.create(bytes);