scoop:scoop.platform:0.1.0
src/fs/file_contents.scoop
Selected production source · src/fs/file_contents.scoop
1
package scoop.platform.fs3
import scoop.platform.io.*5
/**6
* Collects all remaining input into an independent byte array. Path overloads open and close their7
* own file handle.8
*/9
public fun Path.readAllBytes(): Array<Byte> = File.open(this).use { it.readAllBytes() }11
/**12
* Reads all remaining bytes and validates them as UTF-8.13
*/14
public fun Path.readText(): String = File.open(this).use { it.readText() }16
/**17
* Reads all remaining bytes as UTF-8, replacing malformed sequences.18
*/19
public 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, with23
* explicit append selection.24
*/25
public fun Path.writeAllBytes(bytes: List<Byte>, append: Boolean = false) {26
val input = bytes.toArray()27
File.open(this, outputOptions(append)).use { it.writeAllBytes(input) }28
}30
/**31
* Writes the complete UTF-8 encoding of the text without appending a newline.32
*/33
public fun Path.writeText(text: String, append: Boolean = false) {34
File.open(this, outputOptions(append)).use { it.writeText(text) }35
}37
/**38
* Copies input to a destination and returns actual bytes transferred. Byte-source copies borrow39
* both endpoints; path copies own their temporary handles and honor replaceExisting.40
*/41
public 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 -> @Unsafe51
{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
}66
}68
private fun outputOptions(append: Boolean): OpenOptions =69
OpenOptions(read = false, write = true, create = true, append = append, truncate = !append)