Skip to content

Commit f749dc0

Browse files
authored
Correctly write data into sink's internal buffer (#216)
* Correctly write data into sink's internal buffer when using Sink::asNSOutputStream Fixes #215
1 parent 4b0d0f8 commit f749dc0

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

core/apple/src/BuffersApple.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ internal fun Buffer.write(source: CPointer<uint8_tVar>, maxLength: Int) {
2222

2323
val toCopy = minOf(maxLength - currentOffset, Segment.SIZE - tail.limit)
2424
tail.data.usePinned {
25-
memcpy(it.addressOf(tail.pos), source + currentOffset, toCopy.convert())
25+
memcpy(it.addressOf(tail.limit), source + currentOffset, toCopy.convert())
2626
}
2727

2828
currentOffset += toCopy

core/apple/test/SinkNSOutputStreamTest.kt

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,35 @@ import platform.darwin.NSUInteger
1818
import platform.posix.uint8_tVar
1919
import kotlin.test.*
2020

21+
private fun NSOutputStream.write(vararg strings: String) {
22+
for (str in strings) {
23+
str.encodeToByteArray().apply {
24+
assertEquals(size, this.write(this@write))
25+
}
26+
}
27+
}
28+
2129
@OptIn(UnsafeNumber::class)
2230
class SinkNSOutputStreamTest {
31+
32+
@Test
33+
fun multipleWrites() {
34+
val buffer = Buffer()
35+
buffer.asNSOutputStream().apply {
36+
open()
37+
write("hello", " ", "world")
38+
close()
39+
}
40+
assertEquals("hello world", buffer.readString())
41+
42+
RealSink(buffer).asNSOutputStream().apply {
43+
open()
44+
write("hello", " ", "real", " sink")
45+
close()
46+
}
47+
assertEquals("hello real sink", buffer.readString())
48+
}
49+
2350
@Test
2451
fun bufferOutputStream() {
2552
testOutputStream(Buffer(), "abc")

core/apple/test/utilApple.kt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENCE file.
44
*/
55

6-
@file:OptIn(UnsafeNumber::class, ExperimentalForeignApi::class, ExperimentalForeignApi::class)
6+
@file:OptIn(UnsafeNumber::class, ExperimentalForeignApi::class)
77

88
package kotlinx.io
99

@@ -71,3 +71,9 @@ fun NSStreamEvent.asString(): String {
7171
else -> "Unknown event $this"
7272
}
7373
}
74+
75+
fun ByteArray.write(to: NSOutputStream): Int {
76+
this.usePinned {
77+
return to.write(it.addressOf(0).reinterpret(), size.convert()).convert()
78+
}
79+
}

0 commit comments

Comments
 (0)