Scoop API

scoop:scoop.platform:0.1.0

src/fs/native_strings.scoop

Selected production source · src/fs/native_strings.scoop

1package scoop.platform.fs
3import scoop.platform.system.OsString
5/**
6 * Borrows a NUL-terminated native encoding for the callback. Embedded NUL is rejected and the
7 * pointer must not escape.
8 */
9@Unsafe
10public fun <R> OsString.withNativeString(block: (Ptr<Byte>) -> R): R {
11 val source = toByteArray()
12 for (byte in source) {
13 if (byte == 0) throw IllegalArgumentException(Some("native string contains NUL"))
14 }
15 if (source.size == Long.MAX_VALUE) throw ArithmeticException()
16 val bytes = Array<Byte>(source.size + 1L) { index -> if (index == source.size) 0.toByte() else source[index] }
17 return bytes.withDataPointer { pointer, _ -> block(pointer) }
20/**
21 * Borrows the path as a NUL-terminated native byte string for the callback only.
22 */
23@Unsafe
24public fun <R> Path.withNativePath(block: (Ptr<Byte>) -> R): R = toOsString().withNativeString(block)
26/**
27 * Copies a readable NUL-terminated native byte string into OsString. The unsafe caller must keep
28 * the full region valid.
29 */
30@Unsafe
31public fun copyNativeString(pointer: Ptr<Byte>): OsString {
32 val length = nativeStringLength(pointer)
33 return OsString.fromByteArray(Array<Byte>(length) { index -> @Unsafe { return@Array pointer.load(index) } })
36@GCLeaf @Extern(name = "scoop_platform_string_length")
37private fun nativeStringLength(pointer: Ptr<Byte>): Long