blob: d96d49d9ffc7b7e48dce5fd90336114742db8634 [file] [log] [blame]
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03001/*
2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
Sergey Mashkove86eb082017-12-04 18:45:05 +03005package kotlinx.coroutines.experimental.io.jvm.javaio
6
7import kotlinx.coroutines.experimental.io.*
8import java.io.*
9
10/**
11 * Copies up to [limit] bytes from [this] input stream to CIO byte [channel] blocking on reading [this] stream
12 * and suspending on [channel] if required
13 *
14 * @return number of bytes copied
15 */
16suspend fun InputStream.copyTo(channel: ByteWriteChannel, limit: Long = Long.MAX_VALUE): Long {
17 require(limit >= 0) { "Limit shouldn't be negative: $limit" }
18 val buffer = ByteArrayPool.borrow()
19
20 try {
21 var copied = 0L
22 val bufferSize = buffer.size.toLong()
23 while (copied < limit) {
24 val rc = read(buffer, 0, minOf(limit - copied, bufferSize).toInt())
25 if (rc == -1) break
26 else if (rc > 0) {
27 channel.writeFully(buffer, 0, rc)
28 copied += rc
29 }
30 }
31
32 return copied
33 } finally {
34 ByteArrayPool.recycle(buffer)
35 }
36}