Kotlin / kotlinx-io

Kotlin multiplatform I/O library
Apache License 2.0
1.22k stars 56 forks source link

Missing API: buffer builders #168

Open SPC-code opened 1 year ago

SPC-code commented 1 year ago

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.

JakeWharton commented 1 year ago

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

SPC-code commented 1 year ago

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.

JakeWharton commented 1 year ago

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

SPC-code commented 1 year ago

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.

JakeWharton commented 1 year ago

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.