kotlinx-io
kotlinx-io copied to clipboard
Construct a ByteArrayInputStream from a ByteString without copying bytes or using UnsafeByteStringOperations
Creating a ByteArrayInputStream from a ByteString gives us an InputStream, which is used in many contexts in java. My understanding is that it is completely safe, since a ByteArrayInputStream only reads the underlying ByteArray and does not write to it.
Currently, I believe there are only two ways to get a ByteArrayInputStream from a ByteString:
- Use
UnsafeByteStringOperations - Copy the bytes
I am wondering if the library could provide a method to get an InputStream (it doesn't necessarily have to be a ByteArrayInputStream, but why not) that is declared safe and doesn't copy bytes.
It was not considered previously, but in the same way Java stdlib provides StringReader for String, we can also provide an InputStream-view over ByteString.
My understanding is that it is completely safe, since a
ByteArrayInputStreamonly reads the underlyingByteArrayand does not write to it.
It depends: ByteArrayInputStream itself is safe, but its transferTo method exposes internal byte array to an OutputStream which, if implemented maliciously, can mutate array's content.
ByteArrayInputStream itself is safe, but its transferTo method exposes internal byte array
Thanks for pointing that out. I was unsure if there might be some vulnerability like that.
Maybe this library can implement a custom InputStream which wraps around ByteArrayInputStream, but more more strictly preventing the ByteArray from leaking out?
I guess this might mean making transferTo much less efficient, either by copying bytes or by transfering them one at a time. I am curious what is the best solution here.