Scoop API

scoop:scoop.core:0.1.0

src/cstrings.scoop

Selected production source · src/cstrings.scoop

1// Temporary NUL-terminated copies use the ordinary scoped array borrow.
2/**
3 * Copies the string into scoped NUL-terminated UTF-8 storage. Embedded NUL is rejected; the
4 * pointer must not escape the callback.
5 */
6@Unsafe
7public fun <R> String.withCString(block: (Ptr<Int8>) -> R): R {
8 val source = this
9 val length = byteLength
10 var index = 0L
11 while (index < length) {
12 if (coreStringByteAt(source, index) == 0) { throw IllegalArgumentException() }
13 index = index + 1L
14 }
15 val bytes = MutableArray<UInt8>(length + 1L) { index ->
16 if (index == length) { 0u } else { coreStringByteAt(source, index).toUByte() }
17 }
18 return bytes.withDataPointer<UInt8, R>(fun(pointer: Ptr<UInt8>, count: Long): R {
19 @Unsafe { return block(pointer.cast<Int8>()) }
20 })
23@GCLeaf
24@Extern(name = "strlen")
25internal fun coreCStringLength(pointer: Ptr<Int8>): ULong