I need to find a sequence of bytes within a ByteArray, but there doesn't seem to be any direct operations to do so. What's the most direct route to determining if a particular sequence of bytes exists within a ByteArray?
For example, I'd like to capture the range of a sequence (or null) with something like this:
val searchArray = arrayOf(0xF1.toByte(), 0xF2.toByte(), 0xF4.toByte(), 0xF8.toByte())
val range = myByteArray.range(of: searchArray)
I'd also be happy with just the starting index, since I always know the size of my search array.
its too simple to add guava just for it:
fun ByteArray.findFirst(sequence: ByteArray,startFrom: Int = 0): Int {
if(sequence.isEmpty()) throw IllegalArgumentException("non-empty byte sequence is required")
if(startFrom < 0 ) throw IllegalArgumentException("startFrom must be non-negative")
var matchOffset = 0
var start = startFrom
var offset = startFrom
while( offset < size ) {
if( this[offset] == sequence[matchOffset]) {
if( matchOffset++ == 0 ) start = offset
if( matchOffset == sequence.size ) return start
}
else
matchOffset = 0
offset++
}
return -1
}