Skip to content

Improve UnsafeByteStringOperations APIs #259

Open
@joffrey-bion

Description

@joffrey-bion

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() and ByteString.getBackingArrayReference with the @UnsafeByteStringApi annotation
  • make ByteString.Companion.wrap() and ByteString.getBackingArrayReference public
  • rename ByteString.Companion.wrap(array) to wrapUnsafe, or turn it into an extension ByteArray.asByteStringUnsafe (with the conventional as- 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 extension ByteArray.toByteString() (see Replace ByteString(ByteArray) constructor with ByteArray.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().

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions