Scoop API

scoop:scoop.platform:0.1.0

src/system/os_string.scoop

Selected production source · src/system/os_string.scoop

1package scoop.platform.system
3/**
4 * An immutable snapshot of operating-system bytes. It can represent names that are not valid
5 * UTF-8; decoding policy is explicit.
6 */
7public class OsString private constructor(private val bytes: Array<Byte>): Equals<OsString>, Hash {
8 /**
9 * Returns an independent copy of the stored native bytes.
10 */
11 public fun toByteArray(): Array<Byte> = Array<Byte>(bytes.size) { index -> bytes[index] }
13 /**
14 * Copies the UTF-16 code units represented by these UTF-8 or WTF-8 bytes, preserving unpaired
15 * surrogates. Malformed or noncanonical encoding throws CharacterCodingException.
16 */
17 public fun toUtf16(): Array<UShort> = decodeOsUtf16(bytes)
19 /**
20 * Decodes the stored bytes as strict UTF-8, rejecting malformed encoding.
21 */
22 public fun decodeUtf8(): String = String.fromUtf8(bytes)
24 /**
25 * Decodes stored bytes with replacement for malformed UTF-8.
26 */
27 public fun decodeUtf8Lossy(): String = String.fromUtf8Lossy(bytes)
29 /**
30 * Returns a lossy UTF-8 presentation suitable for displaying native names.
31 */
32 public fun display(): String = decodeUtf8Lossy()
34 /**
35 * Compares the exact stored byte sequences.
36 */
37 public override operator fun equals(other: OsString): Boolean =
38 byteContentsEqual(bytes, other.bytes)
39 /**
40 * Hashes the stored bytes consistently with equality.
41 */
42 public override fun hash(): Long = byteContentsHash(bytes)
44 /**
45 * Creates independent native-byte values from text or existing native bytes.
46 */
47 public companion object {
48 /**
49 * Copies the UTF-8 encoding of the supplied text.
50 */
51 public fun fromString(value: String): OsString = fromByteArray(value.toByteArray())
53 /**
54 * Copies arbitrary UTF-16 code units as WTF-8, preserving unpaired surrogates and NUL.
55 */
56 public fun fromUtf16(value: List<UShort>): OsString = OsString(encodeOsUtf16(value))
57 /**
58 * Copies arbitrary native bytes without requiring UTF-8.
59 */
60 public fun fromByteArray(value: List<Byte>): OsString =
61 OsString(Array<Byte>(value.size) { index -> value[index] })
62 }
65internal fun byteContentsEqual(left: Array<Byte>, right: Array<Byte>): Boolean {
66 if (left.size != right.size)
67 return false
68 var index = 0L
69 while (index < left.size) {
70 if (left[index] != right[index])
71 return false
72 index += 1L
73 }
74 return true
77internal fun byteContentsHash(bytes: Array<Byte>): Long {
78 var result = 1L
79 for (value in bytes)
80 result = result * 31L + value.toLong()
81 return result