local asio_error = require 'asio_error'
local fs = require 'filesystem'
local serial_port = require 'serial_port'
local stream = require 'stream'

-- Read a small, trusted source file before creating a sandbox. Emilua's
-- source_tree_cache can then provide this file to the child without granting
-- the child access to the host filesystem.
function read_source(path)
    local size = fs.file_size(path)
    local input = serial_port.new()
    input:assign(fs.open(path, {'read_only'}))

    local data = byte_span.new(size)
    stream.read_all(input, data)
    input:close()
    return tostring(data)
end

-- Read a stream through EOF, but preserve real I/O errors instead of treating
-- every exception as a successful end of input.
function read_to_eof(reader)
    local result = byte_span.new(0)
    while true do
        local buf = byte_span.new(4096)
        local ok, value = pcall(function()
            return reader:read_some(buf)
        end)

        if ok then
            result = byte_span.append(result, buf:first(value))
        elseif value == asio_error.misc.eof then
            return tostring(result)
        else
            error(value)
        end
    end
end
