Skip to content

Instantly share code, notes, and snippets.

@Malinskiy
Created April 28, 2020 09:55
Show Gist options
  • Save Malinskiy/f5fd8a6971139fb56266deb4a78548b8 to your computer and use it in GitHub Desktop.
Save Malinskiy/f5fd8a6971139fb56266deb4a78548b8 to your computer and use it in GitHub Desktop.
class AndroidReadChannel(private val delegate: ByteReadChannel) : ByteReadChannel by delegate {
suspend fun read(): TransportResponse {
val bytes = ByteArray(4)
delegate.readFully(bytes, 0, 4)
val ok = bytes.isOkay()
val message = if (!ok) {
delegate.readFully(bytes, 0, 4)
val responseLength = String(bytes, Const.DEFAULT_TRANSPORT_ENCODING)
val errorMessageLength = responseLength.toIntOrNull(16)
if (errorMessageLength == null) {
log.warn { "Unexpected error message length $responseLength" }
null
} else {
val errorBytes = ByteArray(errorMessageLength)
delegate.readFully(errorBytes, 0, errorMessageLength)
String(errorBytes, Const.DEFAULT_TRANSPORT_ENCODING)
}
} else {
null
}
return TransportResponse(ok, message)
}
private fun ByteArray.isOkay(): Boolean {
return this[0] == 'O'.toByte() &&
this[1] == 'K'.toByte() &&
this[2] == 'A'.toByte() &&
this[3] == 'Y'.toByte()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment