--!strict -- core/Input: turns what the caller passed (a buffer, a string of bytes, or a file path) into a buffer, reading files -- through the host adapter the API passes in (core never requires host itself). -- -- local buf, err, name = Input.resolve(src, opts, host) -- -- A string is a path when opts.path is true, or when the host has a file system and the string looks like a path -- (under 4 KB, no NUL / newline) and the file exists; otherwise it is the data itself (opts.data = true forces that). -- name: the path (for the extension fallback) or opts.name. Never throws. local Err = require("@rosetta/core/Err") local Input = {} export type HostLike = { hasFiles: boolean, readFile: (path: string) -> (buffer?, Err.Err?), exists: (path: string) -> boolean, } -- looksLikePath(s) -> true for short strings without NUL / newline bytes function Input.looksLikePath(s: string): boolean return #s > 0 and #s < 4096 and not string.find(s, "\0", 1, true) and not string.find(s, "[\n\r]") end -- resolve(src, opts?, host?) -> buffer, nil, name? | nil, Err function Input.resolve(src: any, opts: any?, host: HostLike?): (buffer?, Err.Err?, string?) local o = opts or {} local t = type(src) if t == "buffer" then return src, nil, o.name elseif t == "string" then local isPath = false if o.path == true then isPath = true elseif o.data ~= true and host and host.hasFiles and Input.looksLikePath(src) then isPath = host.exists(src) end if isPath then if not host then return nil, Err.new(Err.IO, "no host to read " .. src), nil end local b, err = host.readFile(src) if not b then return nil, err, nil end return b, nil, src end return buffer.fromstring(src), nil, o.name end return nil, Err.new(Err.ARG, "expected a buffer, a string or a path, got " .. typeof(src)), nil end -- extension(name) -> the lower-case extension without the dot ("png"), or nil function Input.extension(name: string?): string? if not name then return nil end local ext = string.match(name, "%.([%w_]+)$") return if ext then string.lower(ext) else nil end -- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive -- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found) function Input.sibling(opts: any?, uri: string): buffer? if type(opts) ~= "table" then return nil end local v: any = nil if type(opts.files) == "table" then v = opts.files[uri] end if v == nil and type(opts.resolve) == "function" then local ok, got = pcall(opts.resolve, uri) v = if ok then got else nil end if type(v) == "string" then return buffer.fromstring(v) end return if type(v) == "buffer" then v else nil end return Input