Skip to content

Commit

Permalink
[resources] Read exactly requested count of bytes from InputStream on…
Browse files Browse the repository at this point in the history
… jvm platforms. (#4943)

In some cases the skip and read methods may handle less bytes then
expected. The PR fixes it by proper API on the JVM and manual check on
the Android.

Fixes #4938

## Testing
I manually checked it on the project from the issue.

## Release Notes
### Fixes - Resources
- Read exactly requested count of bytes from InputStream on jvm
platforms.
  • Loading branch information
terrakok authored Jun 7, 2024
1 parent fc90219 commit 8432577
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,32 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
val resource = getResourceAsStream(path)
val result = ByteArray(size.toInt())
resource.use { input ->
input.skip(offset)
input.read(result, 0, size.toInt())
input.skipBytes(offset)
input.readBytes(result, 0, size.toInt())
}
return result
}

//skipNBytes requires API 34
private fun InputStream.skipBytes(offset: Long) {
var skippedBytes = 0L
while (skippedBytes < offset) {
val count = skip(offset - skippedBytes)
if (count == 0L) break
skippedBytes += count
}
}

//readNBytes requires API 34
private fun InputStream.readBytes(byteArray: ByteArray, offset: Int, size: Int) {
var readBytes = 0
while (readBytes < size) {
val count = read(byteArray, offset + readBytes, size - readBytes)
if (count <= 0) break
readBytes += count
}
}

override fun getUri(path: String): String {
val classLoader = getClassLoader()
val resource = classLoader.getResource(path) ?: run {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
val resource = getResourceAsStream(path)
val result = ByteArray(size.toInt())
resource.use { input ->
input.skip(offset)
input.read(result, 0, size.toInt())
input.skipNBytes(offset)
input.readNBytes(result, 0, size.toInt())
}
return result
}
Expand Down

0 comments on commit 8432577

Please sign in to comment.