scoop:scoop.http.client:0.1.0
src/cache/streams.scoop
Selected production source · src/cache/streams.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.http.HttpField5
import scoop.platform.io.UnexpectedEofException6
import scoop.platform.memory.NativeByteBuffer8
internal class ClientCachedResponseStream(private val snapshot: HttpCacheSnapshot) : ClientResponseStream {9
private var remaining: Long = snapshot.bodyLength10
public override val isReadComplete: Boolean get() = remaining == 0L11
public override val trailers: Array<HttpField>? get() = if (isReadComplete) Some(snapshot.trailers) else None12
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long {13
if (remaining == 0L || count == 0L) return 0L14
val before = buffer.writePosition15
val read = try { snapshot.body.readInto(buffer, if (count < remaining) count else remaining) }16
finally { remaining -= buffer.writePosition - before }17
if (read == 0L) throw UnexpectedEofException()18
return read19
}20
}22
internal class ClientEmptyCachedResponse : ClientResponseStream {23
public override val isReadComplete: Boolean get() = true24
public override val trailers: Array<HttpField>? get() = Some<Array<HttpField>>([])25
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long = 0L26
}28
internal fun clientCacheWriteSource(call: ClientCall, source: AsyncByteSource): AsyncByteSource {29
val cache = call.cache ?: return source30
val writer = cache.writer ?: return source31
return ClientCacheWriteSource(source, writer)32
}34
private class ClientCacheWriteSource(private val source: AsyncByteSource, private val writer: HttpCacheWriter) : AsyncByteSource {35
public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long {36
val before = buffer.writePosition37
val read = source.readInto(buffer, count)38
if (read > 0L) {39
NativeByteBuffer.allocate(if (read < 8192L) read else 8192L).use suspend { copy ->40
var offset = 0L41
while (offset < read) {42
val size = if (read - offset < 8192L) read - offset else 8192L43
copy.clear()44
copy.writeBytes(buffer.getBytes(before + offset, size))45
writer.writeFully(copy)46
offset += size47
}48
}49
}50
return read51
}52
}