/
Writing.kt
59 lines (48 loc) · 1.66 KB
/
Writing.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package io.ktor.utils.io.jvm.nio
import io.ktor.utils.io.*
import java.nio.*
import java.nio.channels.*
/**
* Copy up to [limit] bytes to blocking NIO [channel].
* Copying to a non-blocking channel requires selection and not supported.
* It is suspended if no data are available in a byte channel but may block if destination NIO channel blocks.
*
* @return number of bytes copied
*/
public suspend fun ByteReadChannel.copyTo(channel: WritableByteChannel, limit: Long = Long.MAX_VALUE): Long {
require(limit >= 0L) { "Limit shouldn't be negative: $limit" }
if (channel is SelectableChannel && !channel.isBlocking) {
throw IllegalArgumentException("Non-blocking channels are not supported")
}
if (isClosedForRead) return 0
var copied = 0L
val copy = { bb: ByteBuffer ->
val rem = limit - copied
if (rem < bb.remaining()) {
val l = bb.limit()
bb.limit(bb.position() + rem.toInt())
while (bb.hasRemaining()) {
channel.write(bb)
}
bb.limit(l)
copied += rem
} else {
var written = 0L
while (bb.hasRemaining()) {
written += channel.write(bb)
}
copied += written
}
}
while (copied < limit) {
read(min = 0, consumer = copy)
if (isClosedForRead) break
}
return copied
}
/**
* Copy up to [limit] bytes to blocking [pipe]. A shortcut to copyTo function with NIO channel destination
*
* @return number of bytes were copied
*/
public suspend fun ByteReadChannel.copyTo(pipe: Pipe, limit: Long = Long.MAX_VALUE): Long = copyTo(pipe.sink(), limit)