diff --git a/agrona/src/main/java/org/agrona/io/DirectBufferInputStream.java b/agrona/src/main/java/org/agrona/io/DirectBufferInputStream.java index abd2da15b..1b40a9190 100644 --- a/agrona/src/main/java/org/agrona/io/DirectBufferInputStream.java +++ b/agrona/src/main/java/org/agrona/io/DirectBufferInputStream.java @@ -115,7 +115,7 @@ public int read() throws IOException int b = -1; if (position < length) { - b = buffer.getByte(offset + position); + b = buffer.getByte(offset + position) & 0xFF; ++position; } diff --git a/agrona/src/test/java/org/agrona/io/DirectBufferInputStreamTest.java b/agrona/src/test/java/org/agrona/io/DirectBufferInputStreamTest.java new file mode 100644 index 000000000..133501272 --- /dev/null +++ b/agrona/src/test/java/org/agrona/io/DirectBufferInputStreamTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014 - 2015 Real Logic Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.agrona.io; + +import org.agrona.DirectBuffer; +import org.agrona.concurrent.UnsafeBuffer; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class DirectBufferInputStreamTest +{ + + private static final int END_OF_STREAM_MARKER = -1; + + @Test + public void shouldCorrectlyConvertBytesToPositiveIntegers() throws IOException + { + final byte[] data = {(byte) -1, 0}; + final DirectBuffer buffer = new UnsafeBuffer(data); + final DirectBufferInputStream inputStream = new DirectBufferInputStream(buffer); + + assertEquals(inputStream.read(), 255); + } + + @Test + public void shouldReturnMinusOneOnEndOfStream() throws IOException + { + final byte[] data = {1, 2}; + + final DirectBuffer buffer = new UnsafeBuffer(data); + final DirectBufferInputStream inputStream = new DirectBufferInputStream(buffer); + + assertEquals(inputStream.read(), 1); + assertEquals(inputStream.read(), 2); + assertEquals(inputStream.read(), END_OF_STREAM_MARKER); + } +}