Files
rosetta/src/Formats/data/xml/init.luau
T

58 lines
2.3 KiB
Luau

--!strict
-- data/xml: XML 1.0 files, a thin wrapper over codecs/Xml (which see for the node shape and options). Supports:
-- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not
-- supported: external entities / DTDs, validation.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
-- ------------------------------------------------------------------------------------------------ contract
local XmlFormat = {
name = "xml",
category = "data",
extensions = { "xml", "xsd", "xsl", "xslt", "rss", "atom", "xhtml" },
mime = { "application/xml", "text/xml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml" },
caps = { decode = true, encode = true, namespaces = true, streaming = true },
}
export type DecodeOptions = Xml.DecodeOptions
export type EncodeOptions = Xml.EncodeOptions
-- ------------------------------------------------------------------------------------------------ sniff
function XmlFormat.sniff(r: Bytes.Reader): number
local head = r:peek(64)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.match(head, "^<%?xml[ \t\r\n]") or string.sub(head, 1, 4) == "\255\254<\0" or string.sub(head, 1, 4) == "\254\255\0<" then
return 0.5
end
if string.match(head, "^[ \t\r\n]*<[%a!]") then
return 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function XmlFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.XmlNode?, Err.Err?)
return Xml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), opts)
end
-- ------------------------------------------------------------------------------------------------ encode
function XmlFormat.encode(node: Types.XmlNode, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(node) ~= "table" or type(node.name) ~= "string" then
return nil, Err.new(Err.ARG, "expected an XmlNode")
end
local s, err = Xml.encode(node, opts)
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
return XmlFormat