scoop:scoop.compression:0.1.0
src/asyncio/sink_impl.scoop
Selected production source · src/asyncio/sink_impl.scoop
1
package scoop.compression.asyncio3
import scoop.asyncio.*4
import scoop.compression.*5
import scoop.platform.io.WriteZeroException6
import scoop.platform.memory.NativeByteBuffer8
internal class AsyncCompressionSinkImpl(9
private val sink: AsyncByteSink, loop: EventLoop, resources: CompressionIoResources, owner: AsyncCloseable?10
) : AsyncByteSink, AsyncCloseable {11
private val state: CompressionWriteState = CompressionWriteState(resources)12
private val guard: AsyncCompressionOwner = AsyncCompressionOwner(resources, owner, loop)13
val totals: CompressionTotals get() = state.totals14
val failure: Throwable? get() = guard.failure16
public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long = guard.operation<Long>(17
{ requireCompressionTransfer(count, buffer.readableBytes); state.requireWritable() },18
suspend { if (count == 0L) 0L else writeSome(buffer, count) }19
)21
private suspend fun writeSome(buffer: NativeByteBuffer, count: Long): Long {22
while (true) {23
ensureActive()24
drain()25
val step = state.process(buffer, count)26
drain()27
if (step.consumed > 0L) return step.consumed28
}29
}31
private suspend fun drain() {32
val output = state.buffer33
while (output.readableBytes > 0L) {34
ensureActive()35
val requested = output.readableBytes36
val before = output.readPosition37
val count = try { sink.writeFrom(output, requested) }38
finally { state.recordOutput(output.readPosition - before) }39
requireCompressionProgress(count, requested, output.readPosition - before)40
if (count == 0L) throw WriteZeroException()41
}42
output.clear()43
}45
public override suspend fun flush() {46
guard.operation<Unit>({ Unit }, suspend {47
drain()48
while (true) {49
ensureActive()50
val step = state.flushStep()51
drain()52
if (step.state != CompressionState.NeedOutput) break53
}54
sink.flush()55
})56
}58
suspend fun finish() {59
guard.operation<Unit>({ Unit }, suspend {60
drain()61
while (!state.finished) { ensureActive(); state.finishStep(); drain() }62
})63
}65
public override suspend fun close() { closeCompression(guard) }66
}