Created
April 15, 2020 15:55
-
-
Save diewland/8ff6ab78c90fabd34a54ee90e8dba399 to your computer and use it in GitHub Desktop.
Utility class for read line
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 ReadLine { | |
private val EOL = listOf( | |
13.toByte(), // CR | |
10.toByte() // LR | |
) | |
private val EOL_SIZE = EOL.size | |
private val MSG_MAX_LENGTH = 99 | |
private var line = byteArrayOf() | |
private var reset = false | |
fun feed (data: ByteArray): ByteArray? { | |
// require reset | |
if (reset) { | |
line = byteArrayOf() | |
reset = false | |
} | |
// append data | |
line += data | |
// end with newline, return data | |
if (endWithNewLine(line)) { | |
reset = true | |
return line | |
} | |
// reset if data too long | |
else if (line.size > MSG_MAX_LENGTH) { | |
line = byteArrayOf() | |
} | |
return null | |
} | |
private fun endWithNewLine (data: ByteArray): Boolean { | |
if (data.size <= EOL_SIZE) return false | |
return data.takeLast(EOL_SIZE) == EOL | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment