Scoop API

scoop:scoop.platform:0.1.0

src/fs/file_contents.scoop

Selected production source · src/fs/file_contents.scoop

1package scoop.platform.fs
3import scoop.platform.io.*
5/**
6 * Collects all remaining input into an independent byte array. Path overloads open and close their
7 * own file handle.
8 */
9public fun Path.readAllBytes(): Array<Byte> = File.open(this).use { it.readAllBytes() }
11/**
12 * Reads all remaining bytes and validates them as UTF-8.
13 */
14public fun Path.readText(): String = File.open(this).use { it.readText() }
16/**
17 * Reads all remaining bytes as UTF-8, replacing malformed sequences.
18 */
19public fun Path.readTextLossy(): String = File.open(this).use { it.readTextLossy() }
21/**
22 * Writes all supplied bytes. Path overloads create/open and close their own file handle, with
23 * explicit append selection.
24 */
25public fun Path.writeAllBytes(bytes: List<Byte>, append: Boolean = false) {
26 val input = bytes.toArray()
27 File.open(this, outputOptions(append)).use { it.writeAllBytes(input) }
30/**
31 * Writes the complete UTF-8 encoding of the text without appending a newline.
32 */
33public fun Path.writeText(text: String, append: Boolean = false) {
34 File.open(this, outputOptions(append)).use { it.writeText(text) }
37/**
38 * Copies input to a destination and returns actual bytes transferred. Byte-source copies borrow
39 * both endpoints; path copies own their temporary handles and honor replaceExisting.
40 */
41public fun Path.copyTo(destination: Path, replaceExisting: Boolean = false): Long {
42 return File.open(this).use {
43 input ->
44 val options =
45 OpenOptions(read = false, write = true, create = true, createNew = !replaceExisting)
46 File.open(destination, options).use {
47 output ->
48 input.withHandle {
49 sourceFd -> output.withHandle {
50 destinationFd -> @Unsafe
51 {
52 val same =
53 nativeSameFile(sourceFd, destinationFd).checked(
54 "compare files",
55 Some(destination.toOsString())
56 )
57 if (same != 0L)
58 throw IllegalArgumentException(Some("cannot copy a file onto itself"))
59 }
60 }
61 }
62 output.truncate(0L)
63 input.copyTo(output)
64 }
65 }
68private fun outputOptions(append: Boolean): OpenOptions =
69 OpenOptions(read = false, write = true, create = true, append = append, truncate = !append)