Scoop API

scoop:scoop.http.client:0.1.0

src/cache/streams.scoop

Selected production source · src/cache/streams.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.http.HttpField
5import scoop.platform.io.UnexpectedEofException
6import scoop.platform.memory.NativeByteBuffer
8internal class ClientCachedResponseStream(private val snapshot: HttpCacheSnapshot) : ClientResponseStream {
9 private var remaining: Long = snapshot.bodyLength
10 public override val isReadComplete: Boolean get() = remaining == 0L
11 public override val trailers: Array<HttpField>? get() = if (isReadComplete) Some(snapshot.trailers) else None
12 public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long {
13 if (remaining == 0L || count == 0L) return 0L
14 val before = buffer.writePosition
15 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 read
19 }
22internal class ClientEmptyCachedResponse : ClientResponseStream {
23 public override val isReadComplete: Boolean get() = true
24 public override val trailers: Array<HttpField>? get() = Some<Array<HttpField>>([])
25 public override suspend fun readInto(buffer: NativeByteBuffer, count: Long): Long = 0L
28internal fun clientCacheWriteSource(call: ClientCall, source: AsyncByteSource): AsyncByteSource {
29 val cache = call.cache ?: return source
30 val writer = cache.writer ?: return source
31 return ClientCacheWriteSource(source, writer)
34private 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.writePosition
37 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 = 0L
41 while (offset < read) {
42 val size = if (read - offset < 8192L) read - offset else 8192L
43 copy.clear()
44 copy.writeBytes(buffer.getBytes(before + offset, size))
45 writer.writeFully(copy)
46 offset += size
47 }
48 }
49 }
50 return read
51 }