Skip to content

Commit b5b2b73

Browse files
authored
Fix OutOfMemoryError during media type sniffing (#44)
1 parent 7b64b93 commit b5b2b73

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

readium/shared/src/main/java/org/readium/r2/shared/util/mediatype/SnifferContent.kt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ internal class SnifferFileContent(val file: File) : SnifferContent {
4444
} catch (e: Exception) {
4545
Timber.e(e)
4646
null
47+
} catch (e: OutOfMemoryError) { // We don't want to catch any Error, only OOM.
48+
Timber.e(e)
49+
null
4750
}
4851
}
4952

@@ -54,7 +57,6 @@ internal class SnifferFileContent(val file: File) : SnifferContent {
5457
Timber.e(e)
5558
null
5659
}
57-
5860
}
5961

6062
/** Used to sniff a bytes array. */

readium/shared/src/main/java/org/readium/r2/shared/util/mediatype/SnifferContext.kt

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import org.readium.r2.shared.parser.xml.XmlParser
1818
import org.readium.r2.shared.publication.Manifest
1919
import org.readium.r2.shared.util.archive.Archive
2020
import org.readium.r2.shared.util.archive.DefaultArchiveFactory
21+
import timber.log.Timber
2122
import java.io.InputStream
2223
import java.nio.charset.Charset
2324
import java.util.*
@@ -86,13 +87,17 @@ class SnifferContext internal constructor(
8687
* It will extract the charset parameter from the media type hints to figure out an encoding.
8788
* Otherwise, fallback on UTF-8.
8889
*/
89-
suspend fun contentAsString(): String? {
90-
if (!loadedContentAsString) {
91-
loadedContentAsString = true
92-
_contentAsString = content?.read()?.toString(charset ?: Charset.defaultCharset())
90+
suspend fun contentAsString(): String? =
91+
try {
92+
if (!loadedContentAsString) {
93+
loadedContentAsString = true
94+
_contentAsString = content?.read()?.toString(charset ?: Charset.defaultCharset())
95+
}
96+
_contentAsString
97+
} catch (e: OutOfMemoryError) { // We don't want to catch any Error, only OOM.
98+
Timber.e(e)
99+
null
93100
}
94-
return _contentAsString
95-
}
96101

97102
private var loadedContentAsString: Boolean = false
98103
private var _contentAsString: String? = null

0 commit comments

Comments
 (0)