Skip to content

Commit 8432577

Browse files
authored
[resources] Read exactly requested count of bytes from InputStream on 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.
1 parent fc90219 commit 8432577

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

components/resources/library/src/androidMain/kotlin/org/jetbrains/compose/resources/ResourceReader.android.kt

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,32 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
1313
val resource = getResourceAsStream(path)
1414
val result = ByteArray(size.toInt())
1515
resource.use { input ->
16-
input.skip(offset)
17-
input.read(result, 0, size.toInt())
16+
input.skipBytes(offset)
17+
input.readBytes(result, 0, size.toInt())
1818
}
1919
return result
2020
}
2121

22+
//skipNBytes requires API 34
23+
private fun InputStream.skipBytes(offset: Long) {
24+
var skippedBytes = 0L
25+
while (skippedBytes < offset) {
26+
val count = skip(offset - skippedBytes)
27+
if (count == 0L) break
28+
skippedBytes += count
29+
}
30+
}
31+
32+
//readNBytes requires API 34
33+
private fun InputStream.readBytes(byteArray: ByteArray, offset: Int, size: Int) {
34+
var readBytes = 0
35+
while (readBytes < size) {
36+
val count = read(byteArray, offset + readBytes, size - readBytes)
37+
if (count <= 0) break
38+
readBytes += count
39+
}
40+
}
41+
2242
override fun getUri(path: String): String {
2343
val classLoader = getClassLoader()
2444
val resource = classLoader.getResource(path) ?: run {

components/resources/library/src/desktopMain/kotlin/org/jetbrains/compose/resources/ResourceReader.desktop.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ internal actual fun getPlatformResourceReader(): ResourceReader = object : Resou
1212
val resource = getResourceAsStream(path)
1313
val result = ByteArray(size.toInt())
1414
resource.use { input ->
15-
input.skip(offset)
16-
input.read(result, 0, size.toInt())
15+
input.skipNBytes(offset)
16+
input.readNBytes(result, 0, size.toInt())
1717
}
1818
return result
1919
}

0 commit comments

Comments
 (0)