square / okio

A modern I/O library for Android, Java, and Kotlin Multiplatform.
https://square.github.io/okio/
Apache License 2.0
8.79k stars 1.18k forks source link

buildByteString #611

Open swankjesse opened 5 years ago

swankjesse commented 5 years ago

This would be handy in ~4 places in OkHttp, possibly more elsewhere.

inline fun buildByteString(block: Buffer.() -> Unit): ByteString {
  val buffer = Buffer()
  buffer.block()
  return buffer.readByteString()
}
bnorm commented 5 years ago

There are a couple choice with a function like this.

Location

  1. Top level function buildByteString {...} - single location
  2. ByteString companion function ByteString.build {...} - expect/actual and all that fun but scoped

Conversion

  1. buffer.readByteString() - results in copy
  2. buffer.snapshot() - SegmentedByteString and everything that comes with it

I'm leaning towards ByteString.build {...} and buffer.readByteString(). Could add ByteString.buildSnapshot {...} if we wanted to use buffer.snapshot().

swankjesse commented 5 years ago

I think we should have a thoughtful policy on when to do snapshots. Maybe everywhere the byte string is at least size X, where X is 2 segments or something?

bnorm commented 5 years ago

Are you talking about enhancing readByteString() to return snapshots when the byte count is above some threshold? Or only for this specific builder function? I would make this enhancement to readByteString() so everyone benefits.

swankjesse commented 5 years ago

Exactly right right place for the enhancements!