scoop:scoop.platform:0.1.0
src/io/text.scoop
Selected production source · src/io/text.scoop
1
package scoop.platform.io3
import scoop.bytes.ByteArrayBuilder4
import scoop.platform.memory.NativeByteBuffer6
/**7
* Reads all remaining bytes and validates them as UTF-8.8
*/9
public fun ByteSource.readText(): String = decodeBytes(readAllBytes(), false)10
/**11
* Reads all remaining bytes as UTF-8, replacing malformed sequences.12
*/13
public fun ByteSource.readTextLossy(): String = decodeBytes(readAllBytes(), true)14
/**15
* Reads one UTF-8 line without its line ending, returning None when EOF occurs before any bytes.16
*/17
public fun ByteSource.readLine(): String? = readLineBytes(this, false)18
/**19
* Reads one line with replacement for malformed UTF-8, returning None at empty EOF.20
*/21
public fun ByteSource.readLineLossy(): String? = readLineBytes(this, true)22
/**23
* Writes the complete UTF-8 encoding of the text without appending a newline.24
*/25
public fun ByteSink.writeText(text: String) { writeAllBytes(text.toByteArray()) }26
/**27
* Writes UTF-8 text followed by a newline.28
*/29
public fun ByteSink.writeLine(text: String) { writeText(text); writeText("\n") }31
/**32
* Adapts a borrowed byte sink to TextWriter without assuming close responsibility.33
*/34
public class Utf8Writer public constructor(private val sink: ByteSink) : TextWriter {35
/**36
* Writes the complete UTF-8 encoding to the borrowed sink.37
*/38
public override fun write(text: String) { sink.writeText(text) }39
/**40
* Flushes the borrowed byte sink.41
*/42
public fun flush() { sink.flush() }43
}45
internal fun decodeBytes(bytes: Array<Byte>, lossy: Boolean): String {46
return if (lossy) String.fromUtf8Lossy(bytes) else String.fromUtf8(bytes)47
}49
private fun readLineBytes(source: ByteSource, lossy: Boolean): String? {50
val bytes = ByteArrayBuilder()51
val newline = NativeByteBuffer.allocate(1L).use { buffer ->52
while (true) {53
buffer.clear()54
val count = source.readInto(buffer, 1L)55
requireProgress(count, 1L)56
if (count == 0L) break57
val byte = buffer.readByte()58
if (byte == 10) return@use true59
bytes.append(byte)60
}61
false62
}63
val data = bytes.toByteArray()64
if (data.size == 0L && !newline) return None65
val trim = newline && data.size > 0L && data[data.size - 1L] == 1366
return Some(decodeBytes(if (trim) Array<Byte>(data.size - 1L) { index -> data[index] } else data, lossy))67
}