scoop:scoop.http.asyncio:0.1.0
src/multipart/writer.scoop
Selected production source · src/multipart/writer.scoop
1
package scoop.http.asyncio3
import scoop.asyncio.*4
import scoop.http.*5
import scoop.platform.memory.NativeByteBuffer7
internal class MultipartWriter(sink: AsyncByteSink, owner: AsyncCloseable?, loop: EventLoop, private val state: MultipartWriteState) {8
val finished: Boolean get() = state.finished9
val io: MessageIo<AsyncByteSink> = MessageIo<AsyncByteSink>(sink, owner, loop) { state.close() }11
suspend fun beginPart(head: MultipartPartHead): MultipartPartWriter = io.run({12
val part = MultipartPartWriter(this, head)13
val bytes = state.encoder.beginPart(head)14
state.current = Some(part)15
state.pending = bytes16
}) suspend { sink ->17
state.drain(sink)18
state.current!!19
}21
suspend fun write(part: MultipartPartWriter, buffer: NativeByteBuffer, count: Long): Long = io.run({22
requirePart(part)23
httpCount(count, buffer.readableBytes)24
val capacity = state.output.capacity25
val prefix = if (count < capacity) count else capacity26
state.pending = state.encoder.writeBody(buffer, prefix)27
}) suspend { sink -> state.drain(sink) }29
suspend fun finishPart(part: MultipartPartWriter) {30
io.run({ requirePart(part); state.pending = state.encoder.endPart() }) suspend { sink ->31
state.drain(sink)32
part.complete = true33
state.current = None34
Unit35
}36
}38
suspend fun finish() {39
io.run({ state.pending = state.encoder.finish() }) suspend { sink ->40
state.drain(sink)41
sink.flush()42
state.finished = true43
Unit44
}45
}47
suspend fun flush(part: MultipartPartWriter?) {48
io.run({49
when (part) {50
case Some(val value) -> {51
if (value.closed) throw IoClosedException()52
if (!value.complete) requirePart(value)53
}54
case None -> {}55
}56
}) suspend { sink -> sink.flush() }57
}59
suspend fun closePart(part: MultipartPartWriter) {60
if (part.closed || io.isClosed) { part.closed = true; return }61
httpJob(io.loop, false)62
try { if (!part.complete) io.close() }63
finally { part.closed = true }64
}66
private fun requirePart(part: MultipartPartWriter) {67
if (part.closed) throw IoClosedException()68
if (part.complete || !present(state.current) || state.current!! !== part)69
throw IllegalStateException(Some("this is not the active multipart output part"))70
}71
}