Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

read() in inputstream should return unsigned value #370

Merged
merged 3 commits into from Apr 26, 2022
Merged

read() in inputstream should return unsigned value #370

merged 3 commits into from Apr 26, 2022

Conversation

christiankjaer
Copy link
Contributor

Fixes #369

read() should return a value between 0 and 255 (https://docs.oracle.com/javase/9/docs/api/java/io/InputStream.html#read--)

@@ -2262,7 +2262,8 @@ object ByteVector extends ByteVectorCompanionCrossPlatform {
private val bvlen = bv.size.toInt
private val pos = new CustomAtomicInteger(0)

override def read(): Int = bv.get(pos.getAndIncrement().toLong)
override def read(): Int =
if (pos.get() >= bvlen) -1 else bv.get(pos.getAndIncrement().toLong) & 0xff
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Safer to get current value of pos once instead of calling it twice here.

val p = pos.getAndIncrement()
if (p >= bvlen) -1
else bv.get(p.toLong) & 0xff

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it is a good idea, since available then will return negative values if read() is called at the end of the stream.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, my concern is with thread safety - a race between concurrent read calls and an interleaving of get/get/getAndIncrement/getAndOncrement.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see. So a fix could be in available() instead I guess.

@mpilquist
Copy link
Contributor

Thanks for spotting & fixing. Can we add a unit test for this as well?

@christiankjaer
Copy link
Contributor Author

@mpilquist I have added a small test. read() was not tested at all.

@mpilquist mpilquist merged commit 4186467 into scodec:main Apr 26, 2022
@christiankjaer christiankjaer deleted the bugfix/369 branch April 28, 2022 15:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

ByteVectorInputStream returning value out of range
2 participants