-
Notifications
You must be signed in to change notification settings - Fork 63
Function wrapping ByteArray/ByteString as RawSource #439
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
Comments
For a |
@zhangzih4n thanks for the proposal! It looks reasonable. |
The byte array version is unsafe, and should either do a defensive copy (by just being an alias to Buffer().write) or be added to the existing unsafe function object. |
I found an extension function: Now it should not allocate a new ByteArray
Could you please elaborate on this? I am a beginner and don't quite understand this sentence. |
Sure! The gist is that the copy of data from the mutable byte array occurs when the source is read, not when it is created. This means that if you reuse that mutable byte array and the consumer of your source does not read it in its entirety before new data is written the consumer will see the new data rather than the old data. If you are reusing the byte array, the safe option is to do a whole copy at the time of conversion (i.e., If you are not reusing the byte array then creation of a source from it should still be possible but should be an unsafe operation (since only you can maintain this invariant, not the library). I don't think we need any new APIs for this, as |
Thank you, I understand! I tested the val bytes = "0".encodeToByteArray()
val source = bytes.source().buffered()
val inputStream = bytes.inputStream()
bytes[0] = '1'.code.toByte()
println(bytes.decodeToString())
println(source.readByteArray().decodeToString())
println(inputStream.readAllBytes().decodeToString())
// 1
// 1
// 1 This should be acceptable as it avoids the extra write overhead, just stating it in the comment. |
Sure, but matching java.io behavior has never really been a design goal of the API provided by this library or Okio before it. One of the motivating factors for its existence, in fact, is that java.io has so many fundamental flaws such as the unsafe byte array sharing between layers. |
It is similar to
ByteArray.inputStream()
inkotlin.io
package. It is commonly used, maybe it should be built intokotlinx-io
.A simple implementation:
The text was updated successfully, but these errors were encountered: