scoop:scoop.http.client:0.1.0
src/body/sink.scoop
Selected production source · src/body/sink.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.platform.io.WriteZeroException5
import scoop.platform.memory.NativeByteBuffer7
internal class RequestBodySink(private val destination: AsyncByteSink, private val expected: Long?) : AsyncByteSink {8
private val busy: AtomicBoolean = AtomicBoolean(false)9
private val ended: AtomicBoolean = AtomicBoolean(false)10
private var transferred: Long = 0L11
private var failure: Throwable? = None13
private fun enter() {14
if (!busy.compareAndSet(false, true))15
throw IllegalStateException(Some("request body output already has an operation in progress"))16
}18
private fun requireOpen() {19
if (ended.load()) throw IoClosedException()20
when (failure) { case Some(val error) -> throw error; case None -> {} }21
ensureActive()22
}24
public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long {25
enter()26
try {27
requireOpen()28
if (count < 0L) throw IllegalArgumentException(Some("negative request body write count"))29
val available = buffer.readableBytes30
if (count > available) throw IndexOutOfBoundsException()31
if (count > Long.MAX_VALUE - transferred) throw ArithmeticException()32
if (expected != None && count > expected!! - transferred) {33
val error = RequestBodyLengthException(expected!!, transferred, count)34
failure = Some(error)35
throw error36
}37
try {38
val progress = destination.writeFrom(buffer, count)39
if (progress < 0L || progress > count || available - buffer.readableBytes != progress)40
throw IllegalStateException(Some("invalid request body output progress"))41
if (progress == 0L && count != 0L) throw WriteZeroException()42
return progress43
} catch (error: Throwable) {44
failure = Some(error)45
throw error46
} finally { transferred += available - buffer.readableBytes }47
} finally { busy.store(false) }48
}50
public override suspend fun flush() {51
enter()52
try {53
requireOpen()54
try { destination.flush() }55
catch (error: Throwable) { failure = Some(error); throw error }56
} finally { busy.store(false) }57
}59
internal fun finish(): Long {60
enter()61
try {62
requireOpen()63
if (expected != None && transferred != expected!!)64
throw RequestBodyLengthException(expected!!, transferred)65
return transferred66
} finally { busy.store(false) }67
}69
internal fun end() { ended.store(true) }70
}