scoop:scoop.platform:0.1.0
src/fs/native_strings.scoop
Selected production source · src/fs/native_strings.scoop
1
package scoop.platform.fs3
import scoop.platform.system.OsString5
/**6
* Borrows a NUL-terminated native encoding for the callback. Embedded NUL is rejected and the7
* pointer must not escape.8
*/9
@Unsafe10
public 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) }18
}20
/**21
* Borrows the path as a NUL-terminated native byte string for the callback only.22
*/23
@Unsafe24
public 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 keep28
* the full region valid.29
*/30
@Unsafe31
public 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) } })34
}36
@GCLeaf @Extern(name = "scoop_platform_string_length")37
private fun nativeStringLength(pointer: Ptr<Byte>): Long