Skip to content

Commit 1855228

Browse files
committed
Remove last direct Segment.data use
1 parent e9ef837 commit 1855228

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

core/nodeFilesystemShared/src/files/PathsNodeJs.kt

+15-13
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package kotlinx.io.files
88
import kotlinx.io.*
99
import kotlinx.io.node.buffer
1010
import kotlinx.io.node.fs
11+
import kotlinx.io.unsafe.UnsafeBufferOperations
1112
import kotlinx.io.node.path as nodeJsPath
1213

1314
public actual class Path internal constructor(
@@ -143,6 +144,7 @@ internal class FileSink(path: Path, append: Boolean) : RawSink {
143144
return fd
144145
}
145146

147+
@OptIn(UnsafeIoApi::class)
146148
override fun write(source: Buffer, byteCount: Long) {
147149
check(!closed) { "Sink is closed." }
148150
if (byteCount == 0L) {
@@ -151,20 +153,20 @@ internal class FileSink(path: Path, append: Boolean) : RawSink {
151153

152154
var remainingBytes = minOf(byteCount, source.size)
153155
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
166169
}
167-
source.skip(segmentBytes.toLong())
168170
remainingBytes -= segmentBytes
169171
}
170172
}

0 commit comments

Comments
 (0)