kotlinx-io icon indicating copy to clipboard operation
kotlinx-io copied to clipboard

Missing API: buffer builders

Open SPC-code opened this issue 2 years ago • 5 comments
trafficstars

It is important to be able to construct buffer-like object with builder. In the ktor-io it was ByteReadPacked{}. Here, I suggest this:

fun Buffer(block: Sink.() -> Unit): Buffer

Probably possible to make it inline.

SPC-code avatar Jul 09 '23 19:07 SPC-code

Not sure how useful that is. It's the same as calling apply, only with a less powerful receiver type.

JakeWharton avatar Jul 09 '23 20:07 JakeWharton

It is the same case as with buildString. The operation is frequently used in protocols/formats, and it is useful to make it a stable idiom. Also, it allows to change for more effective implementation later.

The result should be also read-only. But it requires read-only counterpart of a Buffer.

SPC-code avatar Jul 10 '23 05:07 SPC-code

The point of a Buffer is mutability. Perhaps you're looking for buildByteString?

JakeWharton avatar Jul 10 '23 10:07 JakeWharton

ByteString builder does not implement Source interface, so it blocks extensions that are declared on Source. Indeed I am talking about something about ByteString builder, but specialized for binaries.

SPC-code avatar Jul 10 '23 12:07 SPC-code

So something like

fun buildByteString(body: Buffer.() -> Unit): ByteString = Buffer().apply(body).readByteString()

(or potentially with Sink as the lambda receiver)

I'd say the argument for a function is slightly stronger in here than Okio given that this library removed Okio's chaining return types.

JakeWharton avatar Jul 17 '23 19:07 JakeWharton