Files
rosetta/src/Formats/core/Err.luau
T

59 lines
2.1 KiB
Luau

--!strict
-- core/Err: the error values every decoder / encoder returns (`nil, err`; nothing in the library throws on bad data).
-- An Err is a table { code, message, offset?, format? } that prints as "png: CORRUPT at 0x1234: bad filter type 7".
-- Never throws: --!native modules may require it.
--
-- return nil, Err.new(Err.TRUNCATED, "IDAT runs past the end", r.pos)
-- if err.code == Err.UNSUPPORTED then ... end
local Err = {}
-- codes
Err.TRUNCATED = "TRUNCATED" -- the data ends early
Err.CORRUPT = "CORRUPT" -- the data is malformed (bad magic inside, bad table, out-of-range field)
Err.CHECKSUM = "CHECKSUM" -- a CRC / Adler / hash mismatch
Err.UNSUPPORTED = "UNSUPPORTED" -- valid data using a feature this library does not implement, or no encoder
Err.UNKNOWN_FORMAT = "UNKNOWN_FORMAT" -- no format recognised the data / name
Err.LIMIT = "LIMIT" -- over a size limit (opts.maxPixels, opts.maxBytes, ...)
Err.ARG = "ARG" -- a bad argument (wrong type, out-of-range option)
Err.IO = "IO" -- reading or writing a file failed, or the host has no file system
export type Err = {
code: string,
message: string,
offset: number?,
format: string?,
}
local Meta = {}
Meta.__tostring = function(e: Err): string
local s = if e.format then e.format .. ": " .. e.code else e.code
if e.offset then
s ..= string.format(" at 0x%x", e.offset)
end
return s .. ": " .. e.message
end
-- new(code, message, offset?) -> Err
function Err.new(code: string, message: string, offset: number?): Err
return setmetatable({ code = code, message = message, offset = offset, format = nil :: string? }, Meta) :: any
end
-- is(v) -> true when v is an Err
function Err.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == Meta
end
-- wrap(e, format) -> e with its format set (when not set yet); a string becomes a CORRUPT Err. Used by the API to
-- tag errors with the format name.
function Err.wrap(e: any, format: string?): Err
if not Err.is(e) then
e = Err.new(Err.CORRUPT, tostring(e))
end
if e.format == nil then
e.format = format
end
return e
end
return table.freeze(Err)