Skip to content

Correctly write data into sink's internal buffer #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/apple/src/BuffersApple.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal fun Buffer.write(source: CPointer<uint8_tVar>, maxLength: Int) {

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

currentOffset += toCopy
Expand Down
27 changes: 27 additions & 0 deletions core/apple/test/SinkNSOutputStreamTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,35 @@ import platform.darwin.NSUInteger
import platform.posix.uint8_tVar
import kotlin.test.*

private fun NSOutputStream.write(vararg strings: String) {
for (str in strings) {
str.encodeToByteArray().apply {
assertEquals(size, this.write(this@write))
}
}
}

@OptIn(UnsafeNumber::class)
class SinkNSOutputStreamTest {

@Test
fun multipleWrites() {
val buffer = Buffer()
buffer.asNSOutputStream().apply {
open()
write("hello", " ", "world")
close()
}
assertEquals("hello world", buffer.readString())

RealSink(buffer).asNSOutputStream().apply {
open()
write("hello", " ", "real", " sink")
close()
}
assertEquals("hello real sink", buffer.readString())
}

@Test
fun bufferOutputStream() {
testOutputStream(Buffer(), "abc")
Expand Down
8 changes: 7 additions & 1 deletion core/apple/test/utilApple.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENCE file.
*/

@file:OptIn(UnsafeNumber::class, ExperimentalForeignApi::class, ExperimentalForeignApi::class)
@file:OptIn(UnsafeNumber::class, ExperimentalForeignApi::class)

package kotlinx.io

Expand Down Expand Up @@ -71,3 +71,9 @@ fun NSStreamEvent.asString(): String {
else -> "Unknown event $this"
}
}

fun ByteArray.write(to: NSOutputStream): Int {
this.usePinned {
return to.write(it.addressOf(0).reinterpret(), size.convert()).convert()
}
}