Skip to content

Commit

Permalink
Fix close in BufferedReplayInputStream
Browse files Browse the repository at this point in the history
Somehow wrote a bad test, so I didn't catch that
  • Loading branch information
redwarp committed Sep 17, 2022
1 parent 45dcb93 commit 93d30d2
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 18 deletions.
2 changes: 1 addition & 1 deletion decoder/src/main/kotlin/app/redwarp/gif/decoder/Parser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ object Parser {
/**
* Parse gif content from a [ReplayInputStream], keeping the whole content in memory.
*/
fun parse(
private fun parse(
inputStream: ReplayInputStream,
pixelPacking: PixelPacking = PixelPacking.ARGB
): Result<GifDescriptor> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ internal class BufferedReplayInputStream private constructor(
private var reader: Reader? = inputStream?.let { Reader(it) }

override fun seek(position: Int) {
setReplayIfNeeded()
close()
this.state.position = position
}

Expand Down Expand Up @@ -91,12 +91,21 @@ internal class BufferedReplayInputStream private constructor(
}
}

@Synchronized
override fun close() {
reader?.close()
if (loadedData != null) return

reader?.let { reader ->
reader.readAll()
loadedData = reader.toByteArray().also {
reader.close()
this.reader = null
}
}
}

override fun shallowClone(): ReplayInputStream {
setReplayIfNeeded()
close()
return BufferedReplayInputStream(requireNotNull(loadedData), state.copy())
}

Expand All @@ -106,19 +115,6 @@ internal class BufferedReplayInputStream private constructor(
} ?: 0
}

@Synchronized
private fun setReplayIfNeeded() {
if (loadedData != null) return

reader?.let { reader ->
reader.readAll()
loadedData = reader.toByteArray().also {
reader.close()
this.reader = null
}
}
}

private data class State(var position: Int = 0)

private class Reader(inputStream: InputStream) : AutoCloseable {
Expand Down
2 changes: 1 addition & 1 deletion decoder/src/test/kotlin/app/redwarp/gif/decoder/GifTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ class GifTest {

@Test
fun gif_shallowCloned_noIssuesWithConcurrency() = runBlocking {
val gifDescriptor = Parser.parse(File("../assets/domo-no-dispose.gif")).getOrThrow()
val gifDescriptor = Parser.parse(File("../assets/domo-no-dispose.gif").inputStream()).getOrThrow()
val originalGif = Gif(gifDescriptor)

repeat(1000) { id ->
Expand Down

0 comments on commit 93d30d2

Please sign in to comment.