Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-std

Source of release 0.7.1

0.7.1 / src / files / contents.lucb

#==============================================================================================
#
#   contents - Whole-file reads and writes
#
#   DESCRIPTION:
#       Read a file through EOF or up to a limit, as an owned result, and create-or-truncate
#       write.
#
#==============================================================================================

## A whole file's bytes, read through EOF even when its size changes or cannot be sought.
## At most `limit` bytes are accepted: one extra byte may be read to tell an exact fit from
## excess, which fails with too_large rather than truncating. Pass a limit for untrusted or
## possibly unbounded input. The result owns its storage: Luce copies it into `bytes`; a
## Base caller reads `.value` and calls `release()`. On failure nothing is kept.
pub func read(path: c.str, limit: usize = ~(usize)0) -> interop.Owned[const u8[]]!:
    var file = try File.open(path)
    defer file.destroy()
    var bytes: u8[]
    errdefer release_buffer(bytes)
    var used: usize = 0
    var scratch: u8[4096]
    while true:
        let remaining = limit - used
        let requested = 1 if remaining == 0 else (remaining if remaining < scratch.length else scratch.length)
        let count = try file.read(scratch[..<requested])
        if count == 0:
            break
        if remaining == 0:
            error(too_large, "the file exceeds the read limit")
        let needed = used + count
        if needed > bytes.length:
            var capacity = bytes.length *? 2 else limit
            if capacity < 4096:
                capacity = 4096
            if capacity < needed:
                capacity = needed
            if capacity > limit:
                capacity = limit
            if bytes.length == 0:
                bytes = try new u8[capacity] ---
            else:
                bytes = try memory.grow(bytes, capacity)
        memory.copy(bytes[used..], scratch, count)
        used += count
    try file.close()
    if used < bytes.length:
        let exact = try new u8[used] ---
        memory.copy(exact, bytes, used)
        release_buffer(bytes)
        bytes = exact
    return try owned.adopt_bytes(bytes)

## Create or truncate and write all bytes, reporting write and close failures.
## This is neither atomic replacement nor durable sync; use those operations
## explicitly when their guarantees are required.
pub func write(path: c.str, data: const u8[]) -> !:
    var file = try File.open(path, OpenMode.replace)
    defer file.destroy()
    try io.write_all(&file, data)
    try file.close()

func release_buffer(bytes: u8[]):
    if bytes.length > 0:
        free(bytes)