Scoop API

scoop:scoop.platform:0.1.0

src/io/text.scoop

Selected production source · src/io/text.scoop

1package scoop.platform.io
3import scoop.bytes.ByteArrayBuilder
4import scoop.platform.memory.NativeByteBuffer
6/**
7 * Reads all remaining bytes and validates them as UTF-8.
8 */
9public fun ByteSource.readText(): String = decodeBytes(readAllBytes(), false)
10/**
11 * Reads all remaining bytes as UTF-8, replacing malformed sequences.
12 */
13public 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 */
17public fun ByteSource.readLine(): String? = readLineBytes(this, false)
18/**
19 * Reads one line with replacement for malformed UTF-8, returning None at empty EOF.
20 */
21public fun ByteSource.readLineLossy(): String? = readLineBytes(this, true)
22/**
23 * Writes the complete UTF-8 encoding of the text without appending a newline.
24 */
25public fun ByteSink.writeText(text: String) { writeAllBytes(text.toByteArray()) }
26/**
27 * Writes UTF-8 text followed by a newline.
28 */
29public fun ByteSink.writeLine(text: String) { writeText(text); writeText("\n") }
31/**
32 * Adapts a borrowed byte sink to TextWriter without assuming close responsibility.
33 */
34public 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() }
45internal fun decodeBytes(bytes: Array<Byte>, lossy: Boolean): String {
46 return if (lossy) String.fromUtf8Lossy(bytes) else String.fromUtf8(bytes)
49private 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) break
57 val byte = buffer.readByte()
58 if (byte == 10) return@use true
59 bytes.append(byte)
60 }
61 false
62 }
63 val data = bytes.toByteArray()
64 if (data.size == 0L && !newline) return None
65 val trim = newline && data.size > 0L && data[data.size - 1L] == 13
66 return Some(decodeBytes(if (trim) Array<Byte>(data.size - 1L) { index -> data[index] } else data, lossy))