Open
Description
These unsafe operations are really needed for any zero-copy conversion between ByteString
and other immutable APIs, or between representations that the developer knows will not be mutated during their lifespan.
The opt-in annotation should be enough to deter developers from using them, so I believe it's worth making their usage slightly more comfortable. I see 2 main issues right now:
- the object wrapper is not very Kotlinesque, extensions would be better
withByteArrayUnsafe
doesn't return the lambda's result, so it's not convenient to use for conversions. It requires capturing the variable outside the lambda, and this can only be deemed safe by checking the current implementation, which is really not nice (we're already using unsafe APIs, we don't want to rely on implementation details on top of that).
So I would simply suggest the following:
- remove the
UnsafeByteStringOperations
wrapper - mark
ByteString.Companion.wrap()
andByteString.getBackingArrayReference
with the@UnsafeByteStringApi
annotation - make
ByteString.Companion.wrap()
andByteString.getBackingArrayReference
public
- rename
ByteString.Companion.wrap(array)
towrapUnsafe
, or turn it into an extensionByteArray.asByteStringUnsafe
(with the conventionalas-
prefix for methods that just wrap and keep the original instance without copy). If we go the extension route, we could also consider turning the "safe"ByteString(ByteArray)
constructor into the extensionByteArray.toByteString()
(see ReplaceByteString(ByteArray)
constructor withByteArray.toByteString()
#260).
I believe getBackingArrayReference
is already a clear indication that it's unsafe because we're accessing the backing array, so with the unsafe annotation I don't think we would need to rename it differently. But we could go as far as naming it unsafeBackingArrayReference()
.