Created
April 28, 2020 09:55
-
-
Save Malinskiy/f5fd8a6971139fb56266deb4a78548b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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