Fix bugs found while testing BlockDeviceInputStream

This commit is contained in:
Davide Depau 2018-12-24 20:02:18 +01:00
parent a69ce4e4b4
commit 4e2f589d00
Signed by: depau
GPG key ID: C7D999B6A55EFE86

View file

@ -8,6 +8,7 @@ class BlockDeviceInputStream(
private val blockDev: BlockDeviceDriver, private val blockDev: BlockDeviceDriver,
private val prefetchBlocks: Int = 2048 private val prefetchBlocks: Int = 2048
) : InputStream() { ) : InputStream() {
private var neverFetched = true
private val byteBuffer = ByteBuffer.allocate(blockDev.blockSize * prefetchBlocks) private val byteBuffer = ByteBuffer.allocate(blockDev.blockSize * prefetchBlocks)
@ -32,13 +33,19 @@ class BlockDeviceInputStream(
if (blockDev.size - currentBlockOffset < prefetchBlocks) if (blockDev.size - currentBlockOffset < prefetchBlocks)
byteBuffer.limit( byteBuffer.limit(
(currentBlockOffset - blockDev.size).toInt() * blockDev.blockSize (blockDev.size - currentBlockOffset).toInt() * blockDev.blockSize
) )
blockDev.read(currentBlockOffset, byteBuffer) blockDev.read(currentBlockOffset, byteBuffer)
byteBuffer.flip()
} }
private fun fetchNextIfNeeded() { private fun fetchNextIfNeeded() {
if (neverFetched) {
fetch()
neverFetched = false
return
}
if (byteBuffer.hasRemaining()) if (byteBuffer.hasRemaining())
return return
currentBlockOffset++ currentBlockOffset++
@ -87,9 +94,13 @@ class BlockDeviceInputStream(
} }
val newByteOffset = currentByteOffset + actualSkipDistance val newByteOffset = currentByteOffset + actualSkipDistance
currentBlockOffset = newByteOffset / blockDev.blockSize val newBlockOffset = newByteOffset / blockDev.blockSize
if (newBlockOffset != currentBlockOffset) {
currentBlockOffset = newBlockOffset
fetch()
}
fetch()
byteBuffer.position((newByteOffset - currentBlockOffset * blockDev.blockSize).toInt()) byteBuffer.position((newByteOffset - currentBlockOffset * blockDev.blockSize).toInt())
return actualSkipDistance return actualSkipDistance