@@ -8,6 +8,7 @@ package kotlinx.io.files
8
8
import kotlinx.io.*
9
9
import kotlinx.io.node.buffer
10
10
import kotlinx.io.node.fs
11
+ import kotlinx.io.unsafe.UnsafeBufferOperations
11
12
import kotlinx.io.node.path as nodeJsPath
12
13
13
14
public actual class Path internal constructor(
@@ -143,6 +144,7 @@ internal class FileSink(path: Path, append: Boolean) : RawSink {
143
144
return fd
144
145
}
145
146
147
+ @OptIn(UnsafeIoApi ::class )
146
148
override fun write (source : Buffer , byteCount : Long ) {
147
149
check(! closed) { " Sink is closed." }
148
150
if (byteCount == 0L ) {
@@ -151,20 +153,20 @@ internal class FileSink(path: Path, append: Boolean) : RawSink {
151
153
152
154
var remainingBytes = minOf(byteCount, source.size)
153
155
while (remainingBytes > 0 ) {
154
- val head = source.head!!
155
- val segmentBytes = head.limit - head.pos
156
- val buf = buffer.Buffer .allocUnsafe(segmentBytes)
157
- val data = head.data
158
- val pos = head.pos
159
- for (offset in 0 until segmentBytes) {
160
- buf.writeInt8(data[pos + offset], offset)
161
- }
162
- withCaughtException {
163
- fs.writeFileSync(fd, buf)
164
- }?.also {
165
- throw IOException (" Write failed" , it)
156
+ var segmentBytes = 0
157
+ UnsafeBufferOperations .readFromHead(source) { headData, headPos, headLimit ->
158
+ segmentBytes = headLimit - headPos
159
+ val buf = buffer.Buffer .allocUnsafe(segmentBytes)
160
+ for (offset in 0 until segmentBytes) {
161
+ buf.writeInt8(headData[headPos + offset], offset)
162
+ }
163
+ withCaughtException {
164
+ fs.writeFileSync(fd, buf)
165
+ }?.also {
166
+ throw IOException (" Write failed" , it)
167
+ }
168
+ segmentBytes
166
169
}
167
- source.skip(segmentBytes.toLong())
168
170
remainingBytes - = segmentBytes
169
171
}
170
172
}
0 commit comments