Skip to content

Commit

Permalink
refactored ByteArrayInputStream
Browse files Browse the repository at this point in the history
  • Loading branch information
gmuth committed Dec 30, 2024
1 parent d12985a commit d23d2d8
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/main/kotlin/de/gmuth/ipp/core/IppMessage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,7 @@ abstract class IppMessage() {
// --------

fun read(inputStream: InputStream) {
val byteArrayOutputStream = ByteArrayOutputStream()
val byteArraySavingInputStream = object : InputStream() {
override fun read() = inputStream.read()
.also { if (it != -1) byteArrayOutputStream.write(it) }
}
val byteArraySavingInputStream = ByteArraySavingInputStream(inputStream)
val bufferedInputStream = byteArraySavingInputStream.buffered()
try {
IppInputStream(bufferedInputStream).readMessage(this)
Expand All @@ -145,7 +141,8 @@ abstract class IppMessage() {
logger.fine { "documentInputStream class: ${documentInputStream!!.javaClass.simpleName}" }
}
} finally {
rawBytes = byteArrayOutputStream.toByteArray()
// radar: could this include potentially buffered document bytes?
rawBytes = byteArraySavingInputStream.getSavedBytes()
}
}

Expand Down Expand Up @@ -239,10 +236,19 @@ abstract class IppMessage() {
}
}

// --- ByteArraySavingStreams keep a copy of the data read or written ---

private class ByteArraySavingOutputStream(private val outputStream: OutputStream) : OutputStream() {
val byteArrayOutputStream = ByteArrayOutputStream()
fun getSavedBytes(): ByteArray = byteArrayOutputStream.toByteArray()
override fun write(byte: Int) = outputStream.write(byte)
.also { byteArrayOutputStream.write(byte) }
}

private class ByteArraySavingInputStream(private val inputStream: InputStream) : InputStream() {
var byteArrayOutputStream = ByteArrayOutputStream()
fun getSavedBytes(): ByteArray = byteArrayOutputStream.toByteArray()
override fun read() = inputStream.read()
.also { if (it != -1) byteArrayOutputStream.write(it) }
}
}

0 comments on commit d23d2d8

Please sign in to comment.