scoop:scoop.http.client:0.1.0
src/download/copy.scoop
Selected production source · src/download/copy.scoop
1
package scoop.http.client3
import scoop.asyncio.AsyncByteSink4
import scoop.platform.io.WriteZeroException5
import scoop.platform.memory.NativeByteBuffer7
private class ClientDownloadCount(var written: Long)9
internal suspend fun copyClientDownload(download: ClientDownload, response: HttpResponse, destination: AsyncByteSink,10
options: HttpDownloadOptions, offset: Long, total: Long?, resumed: Long = 0L, expected: Long? = None): Long {11
val count = ClientDownloadCount(offset)12
reportClientDownloadProgress(download, response, options, offset, total, resumed)13
NativeByteBuffer.allocate(options.bufferSize).use suspend { buffer ->14
while (true) {15
download.requireActive()16
buffer.clear()17
val received = response.body.readInto(buffer, buffer.capacity)18
if (received == 0L) break19
if (clientPresent(expected) && received > expected!! - (count.written - offset))20
throw HttpResumeException(HttpResumeFailureReason.InvalidRange, "response exceeds its byte range", Some(response.head))21
while (buffer.readableBytes > 0L) {22
val written = destination.writeFrom(buffer, buffer.readableBytes)23
if (written == 0L) throw WriteZeroException()24
count.written += written25
reportClientDownloadProgress(download, response, options, count.written, total, resumed)26
}27
}28
}29
if (clientPresent(expected) && count.written - offset != expected!!)30
throw HttpResumeException(HttpResumeFailureReason.IncompleteRange, "response did not complete its byte range", Some(response.head))31
return count.written32
}34
internal suspend fun reportClientDownloadProgress(download: ClientDownload, response: HttpResponse,35
options: HttpDownloadOptions, written: Long, total: Long?, resumed: Long) {36
download.requireActive()37
options.onProgress(HttpDownloadProgress(response.url, written, total, resumed))38
download.requireActive()39
}