merge ws/cm-formats-datafontvector

This commit is contained in:
4DBug committed 2026-11-01 01:54:18 -05:00
commit 88ad4885f5
42 files changed
+208 -517

No files matched your search

+14 -22
View File
@@ -1,7 +1,6 @@
--!strict
--!native
-- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil,
-- message, offset.
-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset).
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -16,14 +15,13 @@ end }
local SimpleMeta = { __tostring = function(s: any): string
return "cbor.simple(" .. s.value .. ")"
end }
-- tagged(tag, value) -> { tag, value }: a tag this library does not interpret
function Codec.tagged(tag: number, value: any): { tag: number, value: any }
return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any
end
function Codec.isTagged(v: any): boolean
return type(v) == "table" and getmetatable(v) == TaggedMeta
end
-- simple(n) -> an unassigned simple value (0..19, 32..255)
-- unassigned simple values: 0..19, 32..255
function Codec.simple(n: number): { value: number }
return setmetatable({ value = n }, SimpleMeta) :: any
end
@@ -34,7 +32,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = function()
return "undefined"
end }))
-- decimal text of a big-endian unsigned byte string (any length)
local function bigText(s: string): string
local limbs = {} -- base 1e7, little-endian
for i = 1, #s do
@@ -58,7 +55,6 @@ local function bigText(s: string): string
end
return table.concat(out)
end
-- text + 1 for a decimal string
local function incText(s: string): string
local digits: { number } = table.create(#s) :: { number }
for i = 1, #s do
@@ -81,18 +77,18 @@ local function incText(s: string): string
end
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text
null: any?, -- the value for null (default Types.null)
undefined: any?, -- the value for undefined (default Codec.undefined)
bigInts: ("number" | "string")?,
null: any?, -- default Types.null
undefined: any?, -- default Codec.undefined
maxDepth: number?, -- default 512
dates: boolean?, -- tags 0 / 1 as Types.Date (default true)
dates: boolean?, -- default true
}
type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean }
local BREAK = {} -- the 0xFF stop code, inside indefinite items
local BREAK = {} -- 0xFF break stop code
-- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31)
-- additional information 31: indefinite length
local function arg(st: St, ai: number): (number?, string?, string?)
local r = st.r
if ai < 24 then
@@ -169,7 +165,7 @@ local function tag(st: St, t: number, v: any): (any, string?)
n = n * 256 + string.byte(s, i)
end
if n >= 9007199254740992 then
-- exact text; as a number, read back from that text (correctly rounded, unlike the running sum)
-- read back from the exact text: correctly rounded, unlike the running sum
local text = bigText(s)
if t == 3 then
text = incText(text)
@@ -347,7 +343,6 @@ function item(st: St, depth: number): (any, string?)
if v == BREAK then
return nil, "unexpected break"
end
-- bignum content arrives as a buffer: hand the tag its bytes
if (n == 2 or n == 3) and type(v) == "buffer" then
return tag(st, n, buffer.tostring(v))
end
@@ -355,7 +350,6 @@ function item(st: St, depth: number): (any, string?)
end
end
-- decode(r, opts) -> value | nil, message, offset (one item; r is left after it)
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
local o: DecodeOptions = opts or {}
local st: St = {
@@ -378,10 +372,10 @@ end
-- ------------------------------------------------------------------------------------------------ encode
export type EncodeOptions = {
compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds
compactFloats: boolean?, -- default false
sortKeys: boolean?, -- default true
emptyTable: ("array" | "map")?, -- default "array"
dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds
maxDepth: number?, -- default 512 (also catches cycles)
}
@@ -410,7 +404,6 @@ local function head(w: Bytes.Writer, major: number, n: number)
end
end
-- the half-float bits of x when x is exactly representable, else nil
local function toHalf(x: number): number?
if x ~= x then
return 0x7E00
@@ -423,7 +416,7 @@ local function toHalf(x: number): number?
if a == 0 then
return sign
end
local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1
local m, e = math.frexp(a)
local exp = e - 1 + 15
if exp >= 31 then
return nil
@@ -554,7 +547,6 @@ local function enc(st: ESt, v: any, depth: number): boolean
return true
end
-- encode(v, opts) -> buffer | nil, message
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
local o: EncodeOptions = opts or {}
local st: ESt = {
+8 -11
View File
@@ -1,10 +1,7 @@
--!strict
-- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half /
-- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text,
-- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n),
-- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences
-- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats,
-- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values.
-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double
-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences
-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -22,11 +19,11 @@ local Cbor = {
}
export type DecodeOptions = Codec.DecodeOptions & {
all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item)
all: boolean?, -- default false
}
export type EncodeOptions = Codec.EncodeOptions & {
all: boolean?, -- the value is an array of items, written as a sequence
selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7)
all: boolean?,
selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7)
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -91,9 +88,9 @@ function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag
Cbor.tagged = Codec.tagged
Cbor.isTagged = Codec.isTagged
Cbor.simple = Codec.simple -- simple(n) -> a simple value
Cbor.simple = Codec.simple
Cbor.isSimple = Codec.isSimple
Cbor.undefined = Codec.undefined
+13 -18
View File
@@ -1,10 +1,7 @@
--!strict
-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any
-- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded
-- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column
-- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only
-- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters
-- other than the doubled quote, multi-byte delimiters.
-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or
-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode
-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,19 +21,19 @@ local Csv = {
}
export type DecodeOptions = {
delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |)
quote: string?, -- the quote byte (default '"')
header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays)
numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string)
maxRows: number?, -- refuse more rows (default unlimited)
delimiter: string?, -- default ","; "auto": one of , ; tab |
quote: string?, -- default '"'
header: boolean?, -- default false
numbers: boolean?, -- default false
maxRows: number?, -- default unlimited
}
export type EncodeOptions = {
delimiter: string?, -- default ","
quote: string?, -- default '"'
newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv)
quoteAll: boolean?, -- quote every field (default false: only those that need it)
columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order)
header: boolean?, -- keyed rows: write the header row (default true)
newline: string?, -- default "\r\n" (RFC 4180)
quoteAll: boolean?, -- default false
columns: { string }?, -- default: keys in first-seen order
header: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -80,7 +77,6 @@ local function guess(s: string, q: string): string
return best
end
-- rows(s, opts) -> { { string } } | nil, Err
function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
local o: DecodeOptions = opts or {}
local q = o.quote or '"'
@@ -98,7 +94,7 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
local row: { string } = {}
local n = #s
local i = 1
local rowEmpty = true -- the current line has no field text yet (blank lines are skipped)
local rowEmpty = true
while true do
local c = byte(s, i)
local field: string
@@ -141,7 +137,6 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?)
rowEmpty = false
i += 1
else
-- end of the row: CRLF / LF / CR / end of data
if c == 13 and byte(s, i + 1) == 10 then
i += 2
elseif c ~= nil then
+8 -13
View File
@@ -1,11 +1,7 @@
--!strict
-- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code.
-- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value,
-- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at
-- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a
-- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level
-- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested
-- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes.
-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports:
-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline
-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,10 +21,10 @@ local Ini = {
}
export type DecodeOptions = {
inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser)
allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error)
types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans
strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge)
inlineComments: boolean?, -- default false (configparser)
allowNoValue: boolean?, -- default false
types: boolean?,
strict: boolean?, -- default false
}
export type EncodeOptions = {
delimiter: string?, -- default " = "
@@ -92,9 +88,8 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if trimmed == "" then
lastKey = nil
elseif string.match(trimmed, "^[;#]") then
-- a comment line (configparser: also when indented); it does not end a continuation
-- configparser: comment lines may be indented and do not end a continuation
elseif lastKey and indent > lastIndent then
-- continuation of the previous value
local v = trimmed
if o.inlineComments then
v = string.match(v, "^(.-)%s+[;#]") or v
+4 -5
View File
@@ -1,7 +1,6 @@
--!strict
-- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options).
-- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or
-- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas.
-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON
-- Lines. Not supported: JSON5 / comments / trailing commas.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -20,10 +19,10 @@ local JsonFormat = {
}
export type DecodeOptions = Json.DecodeOptions & {
lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value)
lines: boolean?, -- default false
}
export type EncodeOptions = Json.EncodeOptions & {
lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line
lines: boolean?,
}
-- ------------------------------------------------------------------------------------------------ sniff
+11 -17
View File
@@ -1,7 +1,6 @@
--!strict
--!native
-- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with
-- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset.
-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws.
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
@@ -9,7 +8,7 @@ local Codec = {}
local TWO32 = 4294967296
-- an extension value: { type = -128..127, data = buffer }
-- ext type: -128..127
local ExtMeta = { __tostring = function(e: any): string
return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)"
end }
@@ -20,13 +19,11 @@ function Codec.isExt(v: any): boolean
return type(v) == "table" and getmetatable(v) == ExtMeta
end
-- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact
local function u64text(hi: number, lo: number): string
if hi == 0 then
return string.format("%d", lo)
end
local digits = {}
-- long division by 10 on four 16-bit limbs
local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do
local rem = 0
@@ -42,11 +39,11 @@ end
Codec.u64text = u64text
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text
null: any?, -- the value for nil (default Types.null)
maxDepth: number?, -- nesting limit (default 512)
timestamps: boolean?, -- ext -1 as a Types.Date (default true)
ordered: boolean?, -- maps as Types.object with key order (default true)
bigInts: ("number" | "string")?,
null: any?, -- default Types.null
maxDepth: number?, -- default 512
timestamps: boolean?, -- default true
ordered: boolean?, -- default true
}
type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean }
@@ -55,7 +52,6 @@ local function int64(st: St, signed: boolean): any
local r = st.r
local hi, lo = r:u32be(), r:u32be()
if signed and hi >= 0x80000000 then
-- negative: two's complement
local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo
if nlo == TWO32 then
nlo = 0
@@ -239,7 +235,6 @@ function value(st: St, depth: number): (any, string?)
return nil, string.format("reserved type byte 0x%02x", b)
end
-- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it)
function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?)
local o: DecodeOptions = opts or {}
local st: St = {
@@ -259,11 +254,11 @@ end
-- ------------------------------------------------------------------------------------------------ encode
export type EncodeOptions = {
float32: boolean?, -- non-integer numbers as float32 (default false: float64)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
emptyTable: ("array" | "map")?, -- a plain empty table (default "array")
float32: boolean?, -- default false
sortKeys: boolean?, -- default true
emptyTable: ("array" | "map")?, -- default "array"
maxDepth: number?, -- default 512 (also catches cycles)
stringsAsBin: boolean?, -- strings as bin (default false: str)
stringsAsBin: boolean?, -- default false
}
type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? }
@@ -425,7 +420,6 @@ local function enc(st: ESt, v: any, depth: number): boolean
return true
end
-- encode(v, opts) -> buffer | nil, message
function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?)
local o: EncodeOptions = opts or {}
local st: ESt = {
+5 -8
View File
@@ -1,9 +1,7 @@
--!strict
-- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the
-- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as
-- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a
-- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for
-- non-integers unless opts.float32). Not supported: nothing in the spec.
-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as
-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the
-- smallest forms. Not supported: none.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -21,10 +19,10 @@ local Msgpack = {
}
export type DecodeOptions = Codec.DecodeOptions & {
all: boolean?, -- decode every concatenated value into an array (default false: exactly one value)
all: boolean?, -- default false
}
export type EncodeOptions = Codec.EncodeOptions & {
all: boolean?, -- the value is an array of values, written one after another
all: boolean?,
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -83,7 +81,6 @@ function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v)
Msgpack.ext = Codec.ext
Msgpack.isExt = Codec.isExt
+4 -7
View File
@@ -1,10 +1,7 @@
--!strict
-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and
-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and
-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib /
-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression
-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt.
-- Not supported: nothing in the format.
-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT
-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info).
-- Not supported: none.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -54,7 +51,7 @@ function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? }
NbtFormat.info = Nbt.info
NbtFormat.Nbt = Nbt
return NbtFormat
+1 -7
View File
@@ -1,10 +1,6 @@
--!strict
--!native
-- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in
-- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte
-- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs,
-- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles
-- are errors. Never throws: errors return nil, message.
-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes.
local Types = require("@rosetta/Types")
local Binary = {}
@@ -44,7 +40,6 @@ end
export type Options = { bigInts: ("number" | "string")?, maxDepth: number? }
-- decode(buf, base, len, opts) -> value | nil, message
function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?)
if len < 40 then
return nil, "truncated: shorter than header + trailer"
@@ -130,7 +125,6 @@ function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (a
if h >= 0x80000000 and nib == 3 then
v = (h - TWO32) * TWO32 + l
elseif opts and opts.bigInts == "string" and h >= 0x200000 then
-- exact decimal text of h * 2^32 + l
local digits = {}
local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 }
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
+6 -8
View File
@@ -1,9 +1,7 @@
--!strict
-- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is
-- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict ->
-- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data ->
-- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past
-- 2^63. Note: Luau has one number type, so a real with an integral value is written back as <integer>.
-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib),
-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral
-- reals write back as <integer>.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -25,11 +23,11 @@ local Plist = {
}
export type DecodeOptions = {
bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text
bigInts: ("number" | "string")?,
maxDepth: number?, -- default 512
}
export type EncodeOptions = {
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order)
sortKeys: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -300,7 +298,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver)
Plist.uid = Binary.uid
Plist.isUid = Binary.isUid
return Plist
+3 -5
View File
@@ -1,7 +1,5 @@
--!strict
-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over
-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt
-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent).
-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print.
-- Not supported: the 1.21.5 bool(...) / uuid(...) operations.
-- ------------------------------------------------------------------------------------------------ requires
@@ -22,8 +20,8 @@ local SnbtFormat = {
export type DecodeOptions = { maxDepth: number? }
export type EncodeOptions = {
indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact)
quote: string?, -- '"' (default) or "'"
indent: (number | string)?, -- default: compact
quote: string?, -- default '"'
}
-- ------------------------------------------------------------------------------------------------ sniff
+2 -11
View File
@@ -1,8 +1,5 @@
--!strict
-- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with
-- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control
-- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and
-- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based).
-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset).
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
@@ -11,7 +8,7 @@ local Decode = {}
local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char
export type Options = {
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number")
bigInts: ("number" | "string")?, -- default "number"
}
local utf8char = Text.utf8char
@@ -32,7 +29,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return nil
end
-- input checks: BOM, UTF-8, control characters, bare CR
if sub(s, 1, 3) == "\239\187\191" then
s = sub(s, 4)
end
@@ -80,7 +76,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
local function ws(i: number): number
return match(s, "^[ \t]*()", i) :: any
end
-- whitespace, newlines and comments (inside arrays)
local function wsnl(i: number): number
while true do
i = match(s, "^[ \t\n]*()", i) :: any
@@ -114,7 +109,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return fail("bad escape", p)
end
-- strings: value, next | nil
local function basic(i: number): (string?, number)
local parts = {}
local j = i + 1
@@ -204,7 +198,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
return sub(s, j, e - 1) .. string.rep("'", extra), q
end
-- a (dotted) key: { parts }, next | nil
local function key(i: number): ({ string }?, number)
local keys: { string } = {}
while true do
@@ -242,7 +235,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end
end
-- numbers and datetimes
local function number(i: number): (any, number)
local tok = match(s, "^[%+%-]?[%w_%.]+", i)
if not tok then
@@ -556,7 +548,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?)
end
ni += 1
end
-- walk to the parent
local t = root
for j = 1, #keys - 1 do
local k = keys[j]
+3 -10
View File
@@ -1,9 +1,5 @@
--!strict
-- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables
-- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as
-- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date
-- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil,
-- message.
-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws.
local Types = require("@rosetta/Types")
local Json = require("@rosetta/codecs/text/Json")
@@ -12,8 +8,8 @@ local Encode = {}
local format, gsub, find = string.format, string.gsub, string.find
export type Options = {
inline: boolean?, -- write every sub-table as an inline table (default false: [sections])
indent: (number | string)?, -- indent keys of nested sections (default none)
inline: boolean?, -- default false
indent: (number | string)?, -- default none
}
local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" }
@@ -36,7 +32,6 @@ local function keyText(k: string): string
return quote(k)
end
-- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays
local function isMap(t: { [any]: any }): boolean
if Types.isObject(t) then
return true
@@ -56,7 +51,6 @@ local function isDate(v: any): boolean
return Types.Date.is(v)
end
-- an array of tables: non-empty, every element a map
local function isAot(v: any): boolean
if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then
return false
@@ -196,7 +190,6 @@ local function section(st: State, t: any, path: string, out: { string }, inlineA
return true
end
-- encode(t, opts) -> text | nil, message
function Encode.encode(t: any, opts: Options?): (string?, string?)
if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then
return nil, "the top level must be a table with string keys"
+4 -9
View File
@@ -1,11 +1,7 @@
--!strict
-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables,
-- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range
-- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules
-- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables /
-- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to
-- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral
-- values are written as integers).
-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0
-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer /
-- float distinction (integral values write as integers).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,8 +23,7 @@ export type DecodeOptions = Decode.Options
export type EncodeOptions = Encode.Options
-- ------------------------------------------------------------------------------------------------ sniff
-- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same,
-- so this stays low and the extension decides
-- INI looks the same: a [table] or key = value start scores low and the extension decides
function Toml.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.find(head, "%z") then
+2 -3
View File
@@ -1,7 +1,6 @@
--!strict
-- data/xml: XML 1.0 files, a thin wrapper over codecs/text/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.
-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an
-- element. Not supported: external entities / DTDs, validation.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
+6 -17
View File
@@ -1,9 +1,5 @@
--!strict
-- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when
-- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars
-- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as
-- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad
-- values (cycles, functions, collection keys) return nil, message.
-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools).
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
local Parse = require("@rosetta/data/yaml/Parse")
@@ -11,11 +7,11 @@ local Parse = require("@rosetta/data/yaml/Parse")
local Emit = {}
export type Options = {
indent: number?, -- spaces per level (default 2)
all: boolean?, -- the value is an array of documents, written with "---" separators
explicitStart: boolean?, -- start the (first) document with "---" (default false)
sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order)
null: any?, -- the value written as null besides Types.null
indent: number?, -- default 2
all: boolean?,
explicitStart: boolean?, -- default false
sortKeys: boolean?, -- default true
null: any?,
}
local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub
@@ -96,7 +92,6 @@ local function plainOk(s: string): boolean
return true
end
-- a string as a scalar on a line at indentation ind (for block scalars)
local function str(s: string, ind: string, key: boolean): string
if plainOk(s) then
return s
@@ -126,7 +121,6 @@ local keyLess = Types.keyLess
type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? }
-- count references to tables (anchors for those seen twice); false on a cycle
local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then
return true
@@ -150,7 +144,6 @@ local function count(st: St, v: any, onStack: { [any]: boolean }): boolean
return true
end
-- scalar text for a non-collection value, or nil
local function scalar(st: St, v: any, ind: string, key: boolean): string?
local tv = type(v)
if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then
@@ -171,7 +164,6 @@ end
local write: (st: St, v: any, depth: number) -> string?
-- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline)
function write(st: St, v: any, depth: number): string?
local ind = string.rep(" ", st.step * (depth + 1))
local s = scalar(st, v, ind, false)
@@ -244,19 +236,16 @@ local function document(st: St, v: any): string?
if not t then
return nil
end
-- the top level: drop the separator write() put before the first line
if string.sub(t, 1, 1) == "\n" then
return string.sub(t, 2)
end
local body = string.sub(t, 2)
if string.sub(body, 1, 1) == "&" then
-- "&id001\n- a": an anchored top-level collection
return body
end
return body
end
-- encode(v, opts) -> text | nil, message
function Emit.encode(v: any, opts: Options?): (string?, string?)
local o: Options = opts or {}
local st: St = {
+13 -44
View File
@@ -1,11 +1,5 @@
--!strict
-- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized):
-- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with
-- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared
-- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless
-- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core
-- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a
-- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it.
-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it.
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
local Base64 = require("@rosetta/core/Base64")
@@ -15,11 +9,11 @@ local Parse = {}
local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char
export type Options = {
all: boolean?, -- every document as an array (default false: the first document; none -> Types.null)
tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged
maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard
maxDepth: number?, -- nesting limit (default 500)
null: any?, -- the value for null (default Types.null)
all: boolean?, -- default false
tags: ("error" | "ignore")?, -- default "error"
maxAliasNodes: number?, -- default 1e6 (billion laughs guard)
maxDepth: number?, -- default 500
null: any?, -- default Types.null
}
type St = {
@@ -54,7 +48,7 @@ local function col(s: string, p: number): number
return p - q
end
local function isWsEnd(c: number?): boolean -- space, tab, newline or the end
local function isWsEnd(c: number?): boolean
return c == nil or c == 32 or c == 9 or c == 10
end
@@ -66,7 +60,6 @@ local function docMarker(s: string, p: number): boolean
return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3))
end
-- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end)
local function skip(s: string, p: number): number
local n = #s
while p <= n do
@@ -86,7 +79,6 @@ local function skip(s: string, p: number): number
return p
end
-- the number of leading spaces on p's line, and whether a tab comes before p on it
local function lineIndent(s: string, p: number): (number, boolean)
local q = p
while q > 1 and byte(s, q - 1) ~= 10 do
@@ -105,7 +97,6 @@ local function noTabs(s: string, p: number, ind: number?)
end
end
-- skip spaces / tabs on the line
local function skipLine(s: string, p: number): number
return match(s, "^[ \t]*()", p) :: any
end
@@ -120,7 +111,6 @@ end
local utf8char = Text.utf8char
-- ------------------------------------------------------------------------------------------------ resolution
-- the core schema: a plain scalar's value
function Parse.resolve(t: string, nullv: any): any
if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then
return nullv
@@ -168,7 +158,6 @@ local function base64(t: string): buffer?
return (Base64.decode(t))
end
-- a scalar's value given its tag (nil = untagged, "!" = non-specific)
local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any
if tag == nil then
return if plain then Parse.resolve(raw, st.null) else raw
@@ -237,7 +226,6 @@ local function collectionTag(st: St, tag: string?, kind: string, p: number)
end
end
-- expansion size of a value (nodes), memoized
local function size(st: St, v: any): number
if type(v) ~= "table" or v == st.null then
return 1
@@ -257,7 +245,6 @@ end
-- ------------------------------------------------------------------------------------------------ properties
type Props = { anchor: string?, tag: string?, at: number }
-- anchors / tags at p -> props?, the position after them (and the spaces after them)
local function properties(st: St, p: number): (Props?, number)
local s = st.s
local props: Props? = nil
@@ -348,8 +335,7 @@ local function alias(st: St, p: number): (any, number)
end
-- ------------------------------------------------------------------------------------------------ scalars
-- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content.
-- Lines holding only spaces / tabs count as empty.
-- line folding: lines holding only spaces / tabs count as empty
local function fold(s: string, p: number): (string, number)
local empties = 0
local q = p + 1
@@ -385,7 +371,6 @@ local ESC: { [number]: string } = {
[80] = "\226\128\169",
}
-- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote
local function quoted(st: St, p: number, ind: number): (string, number)
local s = st.s
local dq = byte(s, p) == 34
@@ -456,15 +441,13 @@ local function quoted(st: St, p: number, ind: number): (string, number)
end
end
-- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind
-- (block context); flow: the flow-context rules (stops at , [ ] { }).
-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { }
local function plain(st: St, p: number, ind: number, flow: boolean): (string, number)
local s = st.s
local parts: { string } = {}
local i = p
local lastEnd = p
while true do
-- one line's worth
local j = i
local stopAt = nil
while true do
@@ -492,7 +475,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu
if stopAt or byte(s, j) == nil then
return table.concat(parts), lastEnd
end
-- a continuation line?
local f, q = fold(s, j)
local r = skipLine(s, q)
local c = byte(s, r)
@@ -507,7 +489,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu
end
end
-- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it
local function blockScalar(st: St, p: number, ind: number): (string, number)
local s = st.s
local folded = byte(s, p) == 62
@@ -529,7 +510,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
end
local nl = find(s, "\n", q, true)
local lines: { string } = {}
local trailing = 0 -- empty lines after the last content line
local trailing = 0
if not nl then
return "", #s + 1
end
@@ -568,7 +549,6 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
indent = ind + 1
end
end
-- the lines
local r = ls
local pendingEmpty = 0
local endPos = ls
@@ -625,7 +605,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number)
empties = 0
end
end
trailing += empties -- empty lines after the last content line (or all of them)
trailing += empties
body = table.concat(out)
end
if not folded then
@@ -666,7 +646,6 @@ local function enter(st: St, p: number)
end
end
-- a flow node at p (after skip) -> value, next, wasEmpty
local function flowNode(st: St, p: number, ind: number): (any, number, boolean)
local s = st.s
local props, q = properties(st, p)
@@ -688,7 +667,6 @@ local function flowNode(st: St, p: number, ind: number): (any, number, boolean)
local t, r = quoted(st, q, ind)
return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false
elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then
-- an empty node
return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true
elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then
corrupt("unexpected character in a flow collection", q)
@@ -819,7 +797,7 @@ end
-- ------------------------------------------------------------------------------------------------ block
local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number)
-- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':'
-- implicit key: on one line, followed by ':' and a space or the end of the line
local function implicitKey(st: St, p: number): (any, number?)
local s = st.s
local c = byte(s, p)
@@ -847,7 +825,6 @@ local function implicitKey(st: St, p: number): (any, number?)
end
return nil, nil
elseif c == 91 or c == 123 then
-- a flow collection used as a key?
local e = find(s, "\n", p, true) or #s + 1
local line = sub(s, p, e - 1)
if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then
@@ -892,7 +869,7 @@ local function readKey(st: St, p: number, props: Props?): (any, number)
end
k, q = alias(st, p)
q = skipLine(s, q)
q += 1 -- the ':'
q += 1
elseif c == 34 or c == 39 then
local t, r = quoted(st, p, -1)
if find(sub(s, p, r - 1), "\n", 1, true) then
@@ -912,7 +889,6 @@ local function readKey(st: St, p: number, props: Props?): (any, number)
return checkKey(st, k, p), q
end
-- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null
local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number)
local s = st.s
local r = skip(s, p)
@@ -926,7 +902,6 @@ local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapP
return st.null, p
end
-- the value after a ':' (at p, just past it) of a mapping at column mc
local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number)
local s = st.s
local r = skipLine(s, p)
@@ -1044,7 +1019,6 @@ local function blockSeq(st: St, sc: number, p: number): (any, number)
return t, q
end
-- the node at q after its properties (props may be nil); start = where the properties began
local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number)
local s = st.s
local tag = props and props.tag
@@ -1111,9 +1085,6 @@ local function afterProps(st: St, ind: number, start: number, q: number, props:
return finish(st, props, scalarValue(st, text, true, tag, q)), e
end
-- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the
-- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's
-- indentation may follow properties that end their line.
function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number)
local s = st.s
local props, q = properties(st, p)
@@ -1253,7 +1224,6 @@ local function stream(st: St): { any }
p = q
else
if explicit and not find(sub(s, p, q), "\n", 1, true) then
-- content on the "---" line
local ok, _, q2 = pcall(properties, st, q)
local c = byte(s, q2)
if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then
@@ -1282,7 +1252,6 @@ local function stream(st: St): { any }
return docs
end
-- run(text, opts) -> docs | nil, code, message, offset
function Parse.run(text: string, opts: Options?): (any, any, any, any)
local o: Options = opts or {}
local s = text
+3 -9
View File
@@ -1,11 +1,7 @@
--!strict
-- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain /
-- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as
-- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null
-- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams.
-- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables).
-- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore";
-- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings.
-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases
-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style.
-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -47,7 +43,6 @@ function Yaml.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err
function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local docs, code, msg, at = Parse.run(text, opts)
@@ -65,7 +60,6 @@ function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents)
function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local s, err = Emit.encode(value, opts)
if not s then
+6 -14
View File
@@ -1,13 +1,7 @@
--!strict
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in
-- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used),
-- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to
-- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for
-- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and
-- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font
-- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification.
-- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored).
-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1
-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes
-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -27,9 +21,9 @@ local Bdf = {
export type DecodeOptions = { maxGlyphs: number? } -- default 1114112
export type EncodeOptions = {
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
name: string?, -- the FONT (XLFD) name (default built from the font's family / style)
px: number?, -- default 16
chars: (string | { number })?, -- default printable ASCII
name: string?, -- XLFD; default built from the family / style
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -223,7 +217,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil
local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil
local px = strike.size
-- the font bounding box
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
for _, g in strike.glyphs do
if g.width > 0 and g.height > 0 then
@@ -244,7 +237,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
string.format("SIZE %d 75 75", px),
string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0),
}
-- the default glyph: the strike's default, else glyph 0
local defaultIndex = (strike.default or 0) + 1
local props: { { any } } = {
{ "FAMILY_NAME", quote(family) },
+3 -9
View File
@@ -1,10 +1,5 @@
--!strict
-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
-- descriptor has no nesting that matters, no text content).
--
-- Never throws on bad input: parse functions return nil, message.
-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html).
local Bytes = require("@rosetta/core/Bytes")
local Parse = {}
@@ -24,12 +19,12 @@ export type Char = {
export type Desc = {
info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
pages: { string }, -- by page id: page id 0 is pages[1]
chars: { Char },
kernings: { { number } }, -- { first, second, amount }
}
local LIMIT = 1000000 -- chars / kernings
local LIMIT = 1000000
local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
@@ -54,7 +49,6 @@ local function new(): Desc
return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
end
-- one tag's attributes (already split into key -> string) into the description
local function apply(d: Desc, tag: string, a: { [string]: string }): string?
if tag == "info" then
d.info.face = a.face or ""
+15 -30
View File
@@ -1,11 +1,7 @@
--!strict
-- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and
-- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize
-- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are
-- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the
-- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf /
-- woff) into a packed bitmap font with its pages. Written from the BMFont documentation.
-- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha).
-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont
-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages.
-- Not supported: packed multi-channel glyphs (read as alpha).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,25 +20,24 @@ local Bmfont = {
}
export type DecodeOptions = {
pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first)
loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one)
pages: { Types.Image }?, -- page id 0 first
loadPage: ((file: string, page: number) -> any)?,
}
export type EncodeOptions = {
variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text"
px: number?, -- fonts without a BMFont description are baked first (see bake)
px: number?,
chars: (string | { number })?,
file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font")
name: string?, -- the destination's file name (set by the api)
files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes
-- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages
file: string?, -- default: opts.name without its extension, else "font"
name: string?,
files: { [string]: any }?,
encodeImage: ((img: any, format: string) -> (buffer?, any))?,
}
export type BakeOptions = {
px: number?, -- pixels per em (default 32)
chars: (string | { number })?, -- code points to include (default printable ASCII 32..126)
pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096)
padding: number?, -- empty pixels around each glyph (default 1)
file: string?, -- page file name prefix (default "font"): pages are <file>_<n>.png
px: number?, -- default 32
chars: (string | { number })?, -- default printable ASCII 32..126
pageSize: number?, -- default: the smallest power of two that fits, up to 4096
padding: number?, -- default 1
file: string?, -- default "font"; pages are <file>_<n>.png
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -61,7 +56,6 @@ function Bmfont.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the Font value
local Face = {}
Face.__index = Face
@@ -80,10 +74,9 @@ function Face.kern(self: any, a: number, b: number): number
return self._kern[ca.id * 2097152 + cb.id] or 0
end
function Face.outline(_self: any, _g: number): { any }?
return nil -- bitmap font
return nil
end
-- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil
function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?)
local load = loader or self.meta.pageLoader
if type(load) ~= "function" then
@@ -103,8 +96,6 @@ end
local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8
-- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size;
-- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available.
function Face.rasterize(self: any, g: number, px: number?): Types.Image?
local c = self._chars[g]
if not c then
@@ -141,7 +132,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image?
return img
end
-- the Font value of a description
local function face(d: Parse.Desc, variant: string): any
local f: any = setmetatable({
kind = "font",
@@ -244,7 +234,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local d = type(font.meta) == "table" and font.meta.bmfont or nil
local pages = font.pages
if d == nil then
-- page names: opts.file, else the destination's base name (the api passes opts.name), else "font"
local file = opts and opts.file
if file == nil and opts and type(opts.name) == "string" then
file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$")
@@ -262,7 +251,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if not validDesc(d) then
return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont")
end
-- the page images into opts.files, under the names the descriptor gives them
local files = opts and opts.files
local encodeImage = opts and opts.encodeImage
if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then
@@ -310,9 +298,6 @@ local function codepoints(chars: any): { number }
return out
end
-- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are
-- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are
-- kept (rounded to pixels).
function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?)
if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then
return nil, Err.new(Err.ARG, "bake: expected an outline Font")
+5 -8
View File
@@ -1,10 +1,7 @@
--!strict
-- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset,
-- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and
-- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot
-- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string,
-- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C
-- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures.
-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header
-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes.
-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -24,8 +21,8 @@ local Eot = {
export type DecodeOptions = {}
export type EncodeOptions = {
xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false)
rootString: string?, -- the URLs allowed to use the font (default "")
xor: boolean?, -- XOR 0x50; default false
rootString: string?, -- default ""
}
-- ------------------------------------------------------------------------------------------------ constants
+4 -11
View File
@@ -1,10 +1,6 @@
--!strict
-- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the
-- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE
-- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first
-- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI
-- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset).
-- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts.
-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as
-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252.
-- Not supported: vector FNT (Err.UNSUPPORTED), writing.
-- ------------------------------------------------------------------------------------------------ requires
@@ -24,7 +20,7 @@ local Fon = {
caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } },
}
export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first)
export type DecodeOptions = { size: number? } -- default: the first strike
-- ------------------------------------------------------------------------------------------------ sniff
local function isFnt(h: string): boolean
@@ -50,7 +46,6 @@ function Fon.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- one FNT resource -> Font
local function fnt(r: Bytes.Reader): (any, Err.Err?)
local version = r:u16le()
local total = r:u32le()
@@ -145,7 +140,6 @@ local function fnt(r: Bytes.Reader): (any, Err.Err?)
}), nil
end
-- the RT_FONT resources of an NE executable: { { offset, length } }
local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
local rt = r:sub(ne + 0x24, 2):u16le()
local t = r:sub(ne + rt)
@@ -175,7 +169,7 @@ local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?)
return out, nil
end
-- the RT_FONT (8) resources of a PE executable: { { offset, length } }
-- RT_FONT: resource type 8
local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
local h = r:sub(pe + 4, 20)
h:skip(2)
@@ -190,7 +184,6 @@ local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?)
if opt.err or rsrcRva == 0 then
return {}, nil
end
-- the section holding the resources
local secs = r:sub(pe + 24 + optSize, nsec * 40)
local base, rva0 = -1, 0
for _ = 1, nsec do
+5 -12
View File
@@ -1,13 +1,7 @@
--!strict
-- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph
-- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R",
-- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths
-- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster
-- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of
-- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i
-- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph
-- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported:
-- writing, the Hershey "occidental" index files (.hmp), filled rendering.
-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character
-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up.
-- Not supported: writing, .hmp index files, filled rendering.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -26,8 +20,8 @@ local Hershey = {
}
export type DecodeOptions = {
map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii")
strokeWidth: number?, -- stroke width in font units for rasterize (default 2)
map: ("ascii" | "id")?, -- default "ascii"
strokeWidth: number?, -- font units; default 2
maxGlyphs: number?, -- default 65536
}
@@ -93,7 +87,6 @@ function Face.outline(self: any, g: number): { any }?
return out
end
-- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels)
function Face.rasterize(self: any, g: number, px: number): Types.Image?
local gl = self._glyphs[g + 1]
if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then
+2 -14
View File
@@ -1,11 +1,6 @@
--!strict
-- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the
-- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties),
-- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad
-- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES.
-- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets
-- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver
-- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS.
-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver
-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -38,7 +33,6 @@ end
-- ------------------------------------------------------------------------------------------------ decode
type Table = { format: number, size: number, offset: number }
-- a reader positioned after a table's format word, with the integer readers for its byte order
type TR = { r: Bytes.Reader, format: number, big: boolean }
local function open(r: Bytes.Reader, t: Table?): TR?
@@ -91,7 +85,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if r.err then
return nil, r.err
end
-- properties
local props: { [string]: any } = {}
local pt = open(r, tables[PROPERTIES])
if pt then
@@ -122,14 +115,12 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
return nil, Err.new(Err.TRUNCATED, "properties table")
end
end
-- accelerators: ascent / descent
local ascent: number?, descent: number? = nil, nil
local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS])
if at then
at.r:skip(8)
ascent, descent = i32(at), i32(at)
end
-- metrics
local mt = open(r, tables[METRICS])
if not mt then
return nil, Err.new(Err.CORRUPT, "no METRICS table")
@@ -152,7 +143,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
if mt.r.err then
return nil, Err.new(Err.TRUNCATED, "metrics table")
end
-- bitmaps
local bt = open(r, tables[BITMAPS])
if not bt then
return nil, Err.new(Err.CORRUPT, "no BITMAPS table")
@@ -202,7 +192,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local px = Bitmap.unpack(bits, offsets[k], w, h, stride)
glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px }
end
-- encodings
local encodings: { [number]: number } = {}
local default: number? = nil
local et = open(r, tables[BDF_ENCODINGS])
@@ -233,7 +222,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
end
end
-- glyph names
local nt = open(r, tables[GLYPH_NAMES])
if nt then
local n = u32(nt)
+8 -18
View File
@@ -1,14 +1,7 @@
--!strict
-- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2
-- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and
-- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry
-- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map
-- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell
-- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing:
-- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through
-- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps
-- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd
-- project's psf documentation (Andries Brouwer).
-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF /
-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the
-- cell height.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -28,10 +21,10 @@ local Psf = {
export type DecodeOptions = { maxGlyphs: number? } -- default 65536
export type EncodeOptions = {
version: number?, -- 1 or 2 (default 2)
px: number?, -- pixel size for outline fonts (default 16)
chars: (string | { number })?, -- code points for outline fonts (default printable ASCII)
unicode: boolean?, -- write the Unicode table (default true)
version: number?, -- 1 or 2; default 2
px: number?, -- default 16
chars: (string | { number })?, -- default printable ASCII
unicode: boolean?, -- default true
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -103,7 +96,7 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
local map: { [number]: number } = {}
local sequences = {}
local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order
local unicodeTable: { { any } } = {}
if hasTable then
local t = r:sub(glyphAt + count * size)
for i = 0, count - 1 do
@@ -141,7 +134,6 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
inSeq = true
continue
end
-- UTF-8
local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1
if n < 0 then
return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table")
@@ -208,7 +200,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
if n == 0 then
return nil, Err.new(Err.ARG, "no glyphs")
end
-- the cell
local width = 0
for _, g in glyphs do
width = math.max(width, g.advance, g.left + g.width)
@@ -241,7 +232,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?)
end
buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride))
end
-- the Unicode table: each glyph's code point and the extra mappings onto it
local cps: { { number } } = {}
for i = 1, count do
cps[i] = {}
+4 -7
View File
@@ -1,9 +1,7 @@
--!strict
-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the
-- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table,
-- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain /
-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection.
-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing.
-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype
-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap /
-- colour glyphs, GSUB, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -21,7 +19,7 @@ local Ttf = {
}
export type DecodeOptions = {
index: number?, -- the font of a collection (default 0)
index: number?, -- default 0
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -44,7 +42,6 @@ function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- count(r) -> the number of fonts in the file (1 unless a collection)
function Ttf.count(r: Bytes.Reader): number
return TrueType.count(r.buf, r.base)
end
+2 -9
View File
@@ -1,15 +1,8 @@
--!strict
-- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted
-- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side
-- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div,
-- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement;
-- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes,
-- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the
-- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops).
-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored.
local Charstring = {}
export type Result = { cmds: { any }, advance: number, sbx: number }
-- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result
export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? }
local readu8 = buffer.readu8
@@ -18,7 +11,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?)
local cmds: { any } = {}
local stack: { number } = {}
local sp = 0
local ps: { number } = {} -- the PostScript stack callothersubr / pop use
local ps: { number } = {}
local x, y = 0, 0
local advance, sbx = 0, 0
local open = false
+3 -14
View File
@@ -1,12 +1,7 @@
--!strict
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the
-- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox,
-- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV,
-- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring
-- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph
-- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through
-- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple
-- Master and CID-keyed (Type 9 / 11) fonts, writing.
-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font
-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames.
-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -41,7 +36,6 @@ function Type1.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA
local function sections(r: Bytes.Reader): (string?, buffer?, string?)
local b = r.buf
local n = r:size()
@@ -204,7 +198,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4)
local ptext = buffer.tostring(priv)
local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4
-- Subrs
local subrs: { buffer } = {}
local function charstring(p: number, len: number): buffer?
local raw = binaryAt(priv, p, len)
@@ -241,7 +234,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
p = e + n
end
end
-- CharStrings
local names: { string } = {}
local charstrings: { buffer } = {}
local byName: { [string]: number } = {}
@@ -252,7 +244,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
break
end
local e = e0 :: number
-- stop at the end of the dictionary
if string.find(string.sub(ptext, p, s), "%send%s") then
break
end
@@ -281,7 +272,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1]
byName[names[1]], byName[names[nd + 1]] = 0, nd
end
-- the encoding
local encoding: { [number]: string } = {}
if string.find(clear, "/Encoding%s+StandardEncoding") then
for code, gname in GlyphNames.STANDARD do
@@ -306,7 +296,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
cmap[cp] = k - 1
end
end
-- font matrix / bbox
local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]")
local scale = 0.001
if fm then
+3 -5
View File
@@ -1,7 +1,6 @@
--!strict
-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding
-- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended
-- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing.
-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through
-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -20,7 +19,7 @@ local Woff = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
maxBytes: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -29,7 +28,6 @@ function Woff.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err
function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?)
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local base = r.base
+1 -11
View File
@@ -1,10 +1,5 @@
--!strict
-- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table
-- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph,
-- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx
-- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor).
--
-- Never throws: malformed data returns nil, message.
-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx).
local Bytes = require("@rosetta/core/Bytes")
local Brotli = require("@rosetta/codecs/compress/Brotli")
@@ -40,7 +35,6 @@ local function base128(r: Bytes.Reader): number?
return nil
end
-- a cursor over a stream inside the decompressed block
type Stream = { buf: buffer, p: number, e: number, bad: boolean }
local function stream(b: buffer, p: number, n: number): Stream
return { buf = b, p = p, e = p + n, bad = false }
@@ -77,7 +71,6 @@ local function withSign(flag: number, v: number): number
return if band(flag, 1) ~= 0 then v else -v
end
-- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat
local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?)
local h = stream(b, p, n)
su16(h) -- reserved
@@ -132,7 +125,6 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s
return nil, "empty glyph with a bounding box"
end
elseif nc > 0 then
-- simple glyph
local ends = table.create(nc, 0)
local total = 0
for c = 1, nc do
@@ -363,7 +355,6 @@ local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: nu
return out:finish(), nil
end
-- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit")
function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?)
if not r:match("wOF2") then
return nil, "bad signature", "corrupt"
@@ -433,7 +424,6 @@ function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, str
if buffer.len(data) < streamTotal then
return nil, "decompressed stream shorter than the tables", "corrupt"
end
-- the tables, glyf / loca / hmtx rebuilt
local byTag: { [string]: any } = {}
for _, e in dir do
byTag[e.tag] = e
+3 -5
View File
@@ -1,7 +1,6 @@
--!strict
-- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx
-- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF
-- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing.
-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms,
-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -20,7 +19,7 @@ local Woff2 = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
maxBytes: number?, -- default 2^28
}
-- ------------------------------------------------------------------------------------------------ constants
@@ -30,7 +29,6 @@ function Woff2.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err
function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
local maxBytes = (opts and opts.maxBytes) or 2 ^ 28
local at = r.base
+4 -18
View File
@@ -1,11 +1,5 @@
--!strict
-- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes,
-- <style> rules by specificity, style="", inheritance), the shapes as absolute path commands in their user space
-- with the full transform to the root's viewBox space, paints (colours with fill- / stroke-opacity folded into
-- alpha, linear / radial gradients with href inheritance), groups that need their own layer (opacity < 1, or a
-- clip-path) in meta.groups, clip paths resolved per use in meta.clips, <use> / <symbol> / nested <svg> / <switch>.
-- Unsupported elements (text, image, pattern, mask, marker, filter, foreignObject) are counted in meta.unsupported.
-- Never throws.
-- vector/svg/Parse: an SVG document (an Xml tree) to a Types.Vector: the cascade, shapes, paints, groups, clips.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Style = require("@rosetta/vector/svg/Style")
@@ -59,7 +53,7 @@ type Ctx = {
groups: { any },
clips: { any },
unsupported: { [string]: number },
vw: number, -- the current viewport (for percentages)
vw: number,
vh: number,
depth: number,
useDepth: number,
@@ -90,7 +84,7 @@ local function refId(s: string?): string?
return string.match(s, "^%s*#(.-)%s*$") or string.match(s, "^%s*url%(%s*['\"]?#(.-)['\"]?%s*%)")
end
-- the specified properties of an element: presentation attributes < CSS rules (by specificity, then order) < style=""
-- cascade: presentation attributes < CSS rules (by specificity, then order) < style=""
local function specified(n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k, v in pairs(n.attrs :: any) do
@@ -130,7 +124,6 @@ local function specified(n: Node, ctx: Ctx): { [string]: string }
return out
end
-- computed(parent, n) -> the element's computed property strings
local function computed(parent: { [string]: string }, n: Node, ctx: Ctx): { [string]: string }
local out: { [string]: string } = {}
for k in pairs(INHERITED) do
@@ -188,7 +181,6 @@ local function stops(g: Node, ctx: Ctx, seen: { [Node]: boolean }): { { number }
return list
end
-- a gradient attribute, looked up through href templates
local function gattr(g: Node, k: string, ctx: Ctx): string?
local cur: Node? = g
local guard = 0
@@ -250,7 +242,6 @@ local function gradient(g: Node, opacity: number, ctx: Ctx): any
return p
end
-- paint(value, opacity, st) -> Paint | nil (none)
local function paint(value: string?, opacity: number, st: { [string]: string }, ctx: Ctx): any
if value == nil then
return nil
@@ -370,7 +361,6 @@ local function transformOf(n: Node): M
return IDENTITY
end
-- clip(id, ctm, bbox) -> clip index | nil. The clipPath's shapes in root space; objectBoundingBox units mapped to bbox.
local function clip(ref: string, ctm: M, bbox: { number }?, st: { [string]: string }, ctx: Ctx): number?
local cp = ctx.ids[ref]
if cp == nil or local_(cp) ~= "clipPath" then
@@ -508,7 +498,6 @@ local function emitShape(n: Node, st: { [string]: string }, ctm: M, group: numbe
table.insert(ctx.vector.paths, p)
end
-- viewBox + preserveAspectRatio -> the transform from the viewBox to a w x h viewport at (x, y)
function Parse.viewTransform(vb: { number }?, par: string?, x: number, y: number, w: number, h: number): M
if vb == nil or vb[3] <= 0 or vb[4] <= 0 then
return { 1, 0, 0, 1, x, y }
@@ -553,7 +542,6 @@ local function viewBox(n: Node): { number }?
end
local function container(n: Node, st: { [string]: string }, ctm: M, group: number?, ctx: Ctx, children: { Node }?)
-- a layer for opacity / clip-path
local opacity = math.clamp(tonumber(st.opacity or "1") or 1, 0, 1)
local clipRef = refId(st["clip-path"])
local g = group
@@ -563,7 +551,6 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe
local bbox: { number }? = nil
local cp = ctx.ids[clipRef]
if cp and attr(cp, "clipPathUnits") == "objectBoundingBox" then
-- the group's bounding box in its user space: walk once into a scratch vector
local saveV, saveG, saveC = ctx.vector, ctx.groups, ctx.clips
local scratch = Types.Vector.new(0, 0)
ctx.vector, ctx.groups, ctx.clips = scratch, {}, {}
@@ -610,7 +597,7 @@ local function container(n: Node, st: { [string]: string }, ctm: M, group: numbe
end
end
-- a viewport clip (nested svg / symbol: overflow is hidden unless it says otherwise) as a group of its own
-- nested svg / symbol: overflow is hidden unless it says otherwise
local function viewportGroup(n: Node, m: M, x: number, y: number, w: number, h: number, group: number?, ctx: Ctx): number?
local ov = attr(n, "overflow")
if ov == "visible" or ov == "auto" then
@@ -698,7 +685,6 @@ walk = function(n: Node, parentStyle: { [string]: string }, ctm: M, group: numbe
end
-- ------------------------------------------------------------------------------------------------ entry
-- document(doc, opts) -> Vector | nil, message
function Parse.document(doc: any): (Types.Vector?, string?)
local root = doc.root
if root == nil or Xml.localName(root.name) ~= "svg" then
+6 -17
View File
@@ -1,9 +1,6 @@
--!strict
-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3 / SVG 2 "Path data") to absolute M / L / C / Q / Z commands
-- (H / V become L, S / T become C / Q with the reflected control point, arcs become cubic Béziers per the
-- implementation notes F.6 (endpoint to centre parameterisation, out-of-range radii scaled up)); the bounds of a
-- command list; and serialization back to compact path data. Never throws: parsing stops at the first error (the
-- commands so far are kept, as the spec's error handling says).
-- vector/svg/PathData: SVG path data (SVG 1.1 section 8.3, SVG 2 "Path data"); arcs to cubics per implementation notes
-- F.6 (out-of-range radii scaled up); parsing stops at the first error, keeping the commands so far (as the spec says).
local PathData = {}
export type Cmd = { op: string, [number]: number }
@@ -13,7 +10,6 @@ local abs, sqrt, cos, sin, atan2, ceil, pi = math.abs, math.sqrt, math.cos, math
local ARGS = { M = 2, L = 2, H = 1, V = 1, C = 6, S = 4, Q = 4, T = 2, A = 7, Z = 0 }
-- arc(x1, y1, rx, ry, phi, fa, fs, x2, y2, out): cubic segments (absolute) appended to out
local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: number, fa: boolean, fs: boolean, x2: number, y2: number, out: { Cmd })
if x1 == x2 and y1 == y2 then
return
@@ -81,14 +77,13 @@ local function arc(x1: number, y1: number, rx: number, ry: number, phiDeg: numbe
end
PathData.arc = arc
-- parse(d) -> commands (absolute M L C Q Z), ok (false when an error stopped parsing)
function PathData.parse(d: string): ({ Cmd }, boolean)
local out: { Cmd } = {}
local i, n = 1, #d
local cx, cy = 0, 0 -- current point
local sx, sy = 0, 0 -- subpath start
local lcx, lcy = 0, 0 -- last control point (for S / T)
local last = "" -- previous command letter (upper case)
local cx, cy = 0, 0
local sx, sy = 0, 0
local lcx, lcy = 0, 0
local last = ""
local cmd: string? = nil
local rel = false
local nums: { number } = table.create(7) :: { number }
@@ -249,15 +244,12 @@ function PathData.parse(d: string): ({ Cmd }, boolean)
return out, true
end
-- bounds(cmds) -> x0, y0, x1, y1 of every point and control point (nil when empty): the control polygon's box
-- contains the curve; exact enough for objectBoundingBox units on lines, and close for curves
function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?)
local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge
local px, py = 0, 0
for _, c in cmds do
local op = c.op
if op == "C" then
-- the curve's exact extrema
local ax, ay, bx, by, ex, ey = c[1], c[2], c[3], c[4], c[5], c[6]
for axis = 1, 2 do
local p0 = if axis == 1 then px else py
@@ -328,7 +320,6 @@ function PathData.bounds(cmds: { Cmd }): (number?, number?, number?, number?)
return x0, y0, x1, y1
end
-- num(v) -> short text for a coordinate (up to 4 decimals, no trailing zeros)
local function num(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
@@ -343,7 +334,6 @@ local function num(v: number): string
end
PathData.num = num
-- serialize(cmds) -> path data text
function PathData.serialize(cmds: { Cmd }): string
local out = {}
for _, c in cmds do
@@ -360,7 +350,6 @@ function PathData.serialize(cmds: { Cmd }): string
return table.concat(out, " ")
end
-- toRaster(cmds) -> the codecs/image/Raster command list (moveTo / lineTo / quadTo / cubicTo / close)
local RASTER = { M = "moveTo", L = "lineTo", Q = "quadTo", C = "cubicTo", Z = "close" }
function PathData.toRaster(cmds: { Cmd }): { any }
local out = table.create(#cmds)
+3 -15
View File
@@ -1,9 +1,5 @@
--!strict
-- vector/svg/Render: a Types.Vector to an rgba8 Image with codecs/image/Raster (antialiased coverage, nonzero / even-odd,
-- the stroker) and codecs/image/Blend (group layers with opacity and clip masks): fills and strokes with solid colours and
-- linear / radial gradients (objectBoundingBox / userSpaceOnUse units, gradientTransform, pad / reflect / repeat,
-- the SVG 1.1 focal point), dashes, joins, caps, miter limits, per-path opacity, groups and clip paths. The viewBox
-- maps onto the image by meta.preserveAspectRatio. Never throws.
-- vector/svg/Render: a Types.Vector to an rgba8 Image via codecs/image/Raster and codecs/image/Blend.
local Types = require("@rosetta/Types")
local Raster = require("@rosetta/codecs/image/Raster")
local Blend = require("@rosetta/codecs/image/Blend")
@@ -42,7 +38,6 @@ local function stopColor(stops: { { number } }, t: number): (number, number, num
return s[2], s[3], s[4], s[5]
end
-- a paint function(x, y) for a gradient, given the device transform of the path and its user-space bounds
local function gradientFn(p: any, device: M, bbox: { number }?): ((number, number) -> (number, number, number, number))?
local stops = p.stops
if type(stops) ~= "table" or #stops == 0 then
@@ -128,7 +123,6 @@ local function gradientFn(p: any, device: M, bbox: { number }?): ((number, numbe
end
-- ------------------------------------------------------------------------------------------------ dashes
-- subpaths of a command list with their closed flag
local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } }
local out = {}
local cur: { any }? = nil
@@ -151,7 +145,6 @@ local function subpaths(cmds: { any }): { { cmds: { any }, closed: boolean } }
return out
end
-- polyline(cmds, tol) -> { x1, y1, x2, y2, ... } of one subpath (curves subdivided to about tol)
local function polyline(cmds: { any }, tol: number): { number }
local pts: { number } = {}
local px, py = 0, 0
@@ -269,16 +262,14 @@ end
-- ------------------------------------------------------------------------------------------------ rendering
export type Options = {
background: { number }?, -- r, g, b, a under the drawing (default transparent)
tolerance: number?, -- curve flattening in device pixels (default 0.1)
background: { number }?, -- r, g, b, a; default transparent
tolerance: number?, -- device pixels; default 0.1
}
-- the device transform scale (for stroke flattening tolerances)
local function scaleOf(m: M): number
return math.sqrt(math.abs(m[1] * m[4] - m[2] * m[3]))
end
-- rasterize(v, w, h, opts?) -> rgba8 Image
function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?): Types.Image
local o: Options = opts or {}
local img = Types.Image.new(w, h)
@@ -297,7 +288,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local tol = o.tolerance or 0.1
local clipCache: { [number]: buffer } = {}
-- a clip's coverage over the whole image (1 byte per pixel)
local function clipMask(id: number): buffer?
if clipCache[id] then
return clipCache[id]
@@ -325,7 +315,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
clipCache[id] = mask
return mask
end
-- the layer stack: { group id, image }
local stack: { { id: number?, img: Types.Image } } = { { id = nil, img = img } }
local function chain(g: number?): { number }
local out = {}
@@ -365,7 +354,6 @@ function Render.rasterize(v: Types.Vector, w: number, h: number, opts: Options?)
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
-- groups: pop the layers this path is not in, push the ones it needs
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
+2 -13
View File
@@ -1,9 +1,5 @@
--!strict
-- vector/svg/Style: the value syntaxes of SVG presentation attributes: colours (CSS Color 3 names, #rgb / #rgba /
-- #rrggbb / #rrggbbaa, rgb() / rgba() / hsl() / hsla() with numbers or percentages, transparent, currentColor),
-- lengths with units, transform lists, style="" declarations, and a CSS subset for <style> (rules of comma-separated
-- compound selectors made of a type, .classes, #id and *, with specificity; @rules and other combinators are skipped).
-- Never throws.
-- vector/svg/Style: SVG attribute value syntaxes (CSS Color 3, lengths, transform lists) and a <style> CSS subset.
local Raster = require("@rosetta/codecs/image/Raster")
local Style = {}
@@ -57,7 +53,6 @@ local function hue(p: number, q: number, t: number): number
return p
end
-- color(s, current?) -> { r, g, b, a (0..255) } | "none" | nil (not a colour). current: the currentColor value
function Style.color(s: string, current: { number }?): any
s = string.lower((string.gsub(s, "^%s*(.-)%s*$", "%1")))
if s == "none" then
@@ -136,7 +131,7 @@ function Style.color(s: string, current: { number }?): any
return nil
end
-- scan(s, i) -> the SVG number at s[i] (sign? digits? ("." digits)? exponent?), the index after it | nil
-- SVG number: sign? digits? ("." digits)? exponent?
local function scan(s: string, i: number): (number?, number)
local n = #s
local st = i
@@ -194,7 +189,6 @@ local function scan(s: string, i: number): (number?, number)
return tonumber(string.sub(s, st, i - 1)), i
end
-- length(s, ref?, fontSize?) -> number in user units | nil. ref: what 100% is (default 100)
local UNITS: { [string]: number } = { px = 1, pt = 4 / 3, pc = 16, mm = 96 / 25.4, cm = 96 / 2.54, ["in"] = 96, q = 96 / 101.6 }
function Style.length(s: string?, ref: number?, fontSize: number?): number?
if s == nil then
@@ -219,7 +213,6 @@ function Style.length(s: string?, ref: number?, fontSize: number?): number?
return if k then x * k else nil
end
-- numbers(s) -> the numbers of a whitespace / comma separated list ("1, 2 3e1-4"); stops at anything else
function Style.numbers(s: string?): { number }
local out = {}
if s == nil then
@@ -242,7 +235,6 @@ function Style.numbers(s: string?): { number }
return out
end
-- transform(s) -> { a, b, c, d, e, f } (the product of the list) | nil on a syntax error
local mul = Raster.multiply
Style.multiply = mul
function Style.transform(s: string): { number }?
@@ -285,7 +277,6 @@ function Style.transform(s: string): { number }?
return m
end
-- declarations("a: b; c: d") -> { [name] = value } (lower-case names, !important dropped)
function Style.declarations(s: string): { [string]: string }
local out: { [string]: string } = {}
for decl in string.gmatch(s, "[^;]+") do
@@ -333,7 +324,6 @@ local function selector(s: string): Selector?
return sel
end
-- css(text, rules?) -> rules (appended to the list given)
function Style.css(text: string, rules: { Rule }?): { Rule }
local out: { Rule } = rules or {}
text = string.gsub(text, "/%*.-%*/", "")
@@ -362,7 +352,6 @@ function Style.css(text: string, rules: { Rule }?): { Rule }
return out
end
-- matches(sel, tag, id, classes) -> boolean
function Style.matches(sel: Selector, tag: string, id: string?, classes: { [string]: boolean }): boolean
if sel.tag and sel.tag ~= tag then
return false
+1 -6
View File
@@ -1,7 +1,5 @@
--!strict
-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients
-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...>
-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message.
-- vector/svg/Write: a Types.Vector to SVG text; never throws (bad values return nil, message).
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local PathData = require("@rosetta/vector/svg/PathData")
@@ -41,7 +39,6 @@ local function matrix(m: any): string?
return "matrix(" .. table.concat(parts, " ") .. ")"
end
-- write(v) -> SVG text | nil, message
function Write.vector(v: Types.Vector): (string?, string?)
if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then
return nil, "needs a Vector value"
@@ -51,7 +48,6 @@ function Write.vector(v: Types.Vector): (string?, string?)
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local defs = {}
local gradients = 0
-- paints -> attribute values (gradients go to defs)
local function paintAttrs(p: any, which: string): { { any } }
if type(p) ~= "table" then
return { { which, "none" } }
@@ -109,7 +105,6 @@ function Write.vector(v: Types.Vector): (string?, string?)
return "url(#" .. clipIds[id] .. ")"
end
local root = {}
-- the open <g> stack: { id, children }
local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } }
local function chain(g: number?): { number }
local out = {}
+4 -14
View File
@@ -1,15 +1,7 @@
--!strict
-- vector/svg: SVG 1.1 / SVG 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: paths (every command, arcs
-- as cubic Béziers), rect (rounded), circle, ellipse, line, polyline, polygon, transforms, g / a / switch, nested svg
-- (viewBox + preserveAspectRatio), use (also of symbol), defs, presentation attributes, style="", a CSS subset from
-- <style> (type, .class, #id, * and compound selectors, specificity), inheritance, currentColor, fill / stroke /
-- opacity / fill-opacity / stroke-opacity, fill-rule, stroke width / joins / caps / miter limit / dashes, linear and
-- radial gradients (units, gradientTransform, spreadMethod, href inheritance, focal point), group opacity, clip-path
-- (userSpaceOnUse and objectBoundingBox, on shapes and groups), units (px pt pc mm cm in em ex %).
-- Decodes to a Types.Vector (paths in their user space with the full transform to the root's viewBox space; groups and
-- clips in meta); Svg.rasterize(v, w, h) renders it with codecs/image/Raster; encode writes SVG back from a Vector.
-- Not supported (counted in meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject; also
-- conditional processing in switch, CSS combinators / pseudo-classes, non-scaling strokes.
-- vector/svg: SVG 1.1 / 2 static documents (W3C SVG 1.1 2nd ed., SVG 2 CR). Supports: shapes and paths, transforms,
-- nested svg / use / symbol, a CSS subset, gradients, clip-path, group opacity, strokes, dashes, units. Not supported
-- (meta.unsupported): text, image, pattern, mask, marker, filter, foreignObject, switch conditions, CSS combinators.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -32,7 +24,7 @@ local Svg = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 64 MB)
maxBytes: number?, -- default 64 MB
}
export type EncodeOptions = {}
export type RasterizeOptions = Render.Options
@@ -77,8 +69,6 @@ function Svg.encode(v: Types.Vector, opts: EncodeOptions?): (buffer?, Err.Err?)
end
-- ------------------------------------------------------------------------------------------------ extras
-- rasterize(v, w?, h?, opts?) -> rgba8 Image | nil, Err. w / h default to the vector's size (rounded up); the viewBox
-- maps onto w x h by its preserveAspectRatio.
function Svg.rasterize(v: Types.Vector, w: number?, h: number?, opts: RasterizeOptions?): (Types.Image?, Err.Err?)
if type(v) ~= "table" or type(v.paths) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Vector value")
+4 -11
View File
@@ -1,12 +1,10 @@
--!strict
-- vector/tiled/Data: tile layer data shared by the TMX and TMJ halves: CSV text, base64 (uncompressed, zlib, gzip)
-- to gids and back; property values and their types; number formatting. Never throws.
-- vector/tiled/Data: tile layer data shared by TMX and TMJ: CSV, base64 (raw / zlib / gzip), properties, numbers.
local Base64 = require("@rosetta/core/Base64")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Data = {}
-- csv(text) -> { gid } (any whitespace / commas between the numbers) | nil, message
function Data.csv(text: string): ({ number }?, string?)
local out = {}
for tok in string.gmatch(text, "[^,%s]+") do
@@ -19,7 +17,6 @@ function Data.csv(text: string): ({ number }?, string?)
return out, nil
end
-- base64(text, compression) -> { gid } | nil, message, unsupported?
function Data.base64(text: string, compression: string?): ({ number }?, string?, boolean?)
local raw, err = Base64.decode(text)
if not raw then
@@ -49,7 +46,6 @@ function Data.base64(text: string, compression: string?): ({ number }?, string?,
return out, nil, nil
end
-- toBase64(gids, compression?, level?) -> text | nil, message
function Data.toBase64(gids: { number }, compression: string?, level: number?): (string?, string?)
local b = buffer.create(#gids * 4)
for i, g in gids do
@@ -73,7 +69,7 @@ function Data.toBase64(gids: { number }, compression: string?, level: number?):
return Base64.encode(b), nil
end
-- num(v) -> text: integers without a fraction (gids up to 2^32 too), others in the shortest form both runtimes print
-- integers without a fraction (gids up to 2^32), others in the shortest form both runtimes print
function Data.num(v: number): string
if v % 1 == 0 and math.abs(v) < 2 ^ 53 then
return string.format("%.0f", v)
@@ -85,7 +81,7 @@ function Data.num(v: number): string
return s
end
-- csvText(gids, width) -> "1,2,3,\n4,5,6" (Tiled's layout: one row per line)
-- Tiled's CSV layout: one row per line
function Data.csvText(gids: { number }, width: number): string
local rows = {}
local row = {}
@@ -102,7 +98,7 @@ function Data.csvText(gids: { number }, width: number): string
return "\n" .. table.concat(rows, ",\n") .. "\n"
end
-- color(s) -> Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque (nil stays nil)
-- Tiled's canonical colour text: lower case "#rrggbb", or "#aarrggbb" when not opaque
function Data.color(s: string?): string?
if type(s) ~= "string" then
return nil
@@ -114,7 +110,6 @@ function Data.color(s: string?): string?
return "#" .. h
end
-- property values: TMX / TMJ type names -> a Luau value from text
function Data.value(typ: string, text: string): any
if typ == "int" or typ == "float" or typ == "object" then
return tonumber(text) or 0
@@ -126,7 +121,6 @@ function Data.value(typ: string, text: string): any
return text
end
-- typeOf(v, declared?) -> the Tiled type to write for v
function Data.typeOf(v: any, declared: string?): string
if declared then
return declared
@@ -141,7 +135,6 @@ function Data.typeOf(v: any, declared: string?): string
return "string"
end
-- sortedKeys(t) -> its string keys, sorted
function Data.sortedKeys(t: { [any]: any }): { string }
local out = {}
for k in pairs(t) do
+1 -6
View File
@@ -1,6 +1,5 @@
--!strict
-- vector/tiled/Tmj: the TMJ (JSON) half of vector/tiled: a decoded JSON value <-> a Types.TileMap, and TSJ
-- tilesets. JSON map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
-- vector/tiled/Tmj: TMJ / TSJ (JSON map format, Tiled 1.12 docs) <-> a Types.TileMap.
local Types = require("@rosetta/Types")
local Data = require("@rosetta/vector/tiled/Data")
@@ -245,7 +244,6 @@ layer = function(v: any, depth: number): (any, string?, boolean?)
return nil, "unknown layer type " .. tostring(v.type)
end
-- tileset(v) -> Tileset (a map's entry, or a .tsj root)
function Tmj.tileset(v: any): any
local ts: any = {
firstGid = n(v.firstgid, 1),
@@ -297,7 +295,6 @@ function Tmj.tileset(v: any): any
return ts
end
-- read(value) -> TileMap | nil, message, unsupported?
function Tmj.read(v: any): (any, string?, boolean?)
if type(v) ~= "table" or (v.type ~= nil and v.type ~= "map") then
return nil, "not a Tiled map (type is not \"map\")"
@@ -535,7 +532,6 @@ writeLayer = function(l: any, o: WriteOptions): (any, string?)
return obj(fields), nil
end
-- tilesetValue(ts, inMap) -> a JSON object
function Tmj.tilesetValue(ts: any, inMap: boolean): any
if inMap and type(ts.source) == "string" then
return obj({ { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
@@ -590,7 +586,6 @@ function Tmj.tilesetValue(ts: any, inMap: boolean): any
})
end
-- write(map, opts) -> a JSON value | nil, message
function Tmj.write(map: any, o: WriteOptions): (any, string?)
local layers = {}
for _, l in map.layers do
+1 -9
View File
@@ -1,6 +1,5 @@
--!strict
-- vector/tiled/Tmx: the TMX (XML) half of vector/tiled: a codecs/text/Xml tree <-> a Types.TileMap, and TSX tilesets.
-- TMX map format, Tiled 1.12 docs. Never throws: failures return nil, message, unsupported?.
-- vector/tiled/Tmx: TMX / TSX (TMX map format, Tiled 1.12 docs) <-> a Types.TileMap.
local Xml = require("@rosetta/codecs/text/Xml")
local Types = require("@rosetta/Types")
local Data = require("@rosetta/vector/tiled/Data")
@@ -28,7 +27,6 @@ local function flag(n: Node, k: string, default: boolean): boolean
end
-- ------------------------------------------------------------------------------------------------ read
-- <properties> -> values, types (types only for the non-string ones)
local function properties(n: Node?): ({ [string]: any }, { [string]: string }?)
local props: { [string]: any } = {}
local types: { [string]: string }? = nil
@@ -68,7 +66,6 @@ local function withProps(t: any, n: Node)
end
end
-- the gids of a <data> (or <chunk>) node
local function gids(d: Node, encoding: string?, compression: string?): ({ number }?, string?, boolean?)
if encoding == "csv" then
return Data.csv(Xml.text(d))
@@ -233,7 +230,6 @@ layer = function(n: Node): (any, string?, boolean?)
return nil
end
-- a <tileset> element (in a map, or a .tsx root) -> Tileset
function Tmx.tileset(n: Node): any
local ts: any = {
firstGid = num(n, "firstgid", 1),
@@ -287,7 +283,6 @@ function Tmx.tileset(n: Node): any
return ts
end
-- read(root) -> TileMap | nil, message, unsupported?
function Tmx.read(root: Node): (any, string?, boolean?)
if root.name ~= "map" then
return nil, "the root element is <" .. root.name .. ">, not <map>"
@@ -330,7 +325,6 @@ end
type Attrs = { [string]: string }
local function el(name: string, attrs: { { any } }, children: { any }?): Node
-- attrs in order; nil / default values dropped by the caller
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
@@ -533,7 +527,6 @@ writeLayer = function(l: any, o: WriteOptions): (Node?, string?)
return nil, "unknown layer type " .. tostring(t)
end
-- tilesetNode(ts, inMap) -> <tileset>
function Tmx.tilesetNode(ts: any, inMap: boolean): Node
if inMap and type(ts.source) == "string" then
return el("tileset", { { "firstgid", ts.firstGid or 1 }, { "source", ts.source } })
@@ -578,7 +571,6 @@ function Tmx.tilesetNode(ts: any, inMap: boolean): Node
}, kids)
end
-- write(map, opts) -> an XML document node | nil, message
function Tmx.write(map: any, o: WriteOptions): (Node?, string?)
local kids = {}
addProps(kids, map)
+8 -17
View File
@@ -1,14 +1,7 @@
--!strict
-- vector/tiled: Tiled maps, TMX (XML) and TMJ (JSON), and standalone TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map
-- Format", "JSON Map Format"). Supports: every orientation's attributes, tile layers (CSV, base64 uncompressed / zlib /
-- gzip, the old <tile gid> XML), infinite maps (chunks), flip bits kept in the gids, object groups (rectangles,
-- ellipses, points, polygons, polylines, text, tile objects, templates as references), image layers, group layers,
-- typed custom properties (string / int / float / bool / color / file / object / class) on everything, tilesets
-- (embedded, or external references kept as `source`), their image as a path (imageSource: tileset images stay
-- references), per-tile class, properties, images, animations and collision object groups. Both flavours decode to the
-- same Types.TileMap and encode from it: opts.format = "tmx" (default: the source's flavour) or "tmj" / "json".
-- Not supported: zstd-compressed layer data (Err.UNSUPPORTED), Wang sets / terrains (dropped), loading external
-- tilesets or images (callers resolve `source` / `imageSource` paths themselves).
-- vector/tiled: Tiled maps, TMX (XML) / TMJ (JSON), and TSX / TSJ tilesets (Tiled 1.12 docs: "TMX Map Format", "JSON
-- Map Format"). Supports: every orientation, tile / object / image / group layers, infinite maps, typed properties,
-- tilesets. Not supported: zstd layer data (Err.UNSUPPORTED), Wang sets / terrains, loading external tilesets / images.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
@@ -31,14 +24,14 @@ local Tiled = {
}
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 256 MB)
maxBytes: number?, -- default 256 MB
}
export type EncodeOptions = {
format: string?, -- "tmx" | "tsx" (XML) or "tmj" | "tsj" | "json" (JSON); default: the source's flavour, else tmx
format: string?, -- "tmx" | "tsx" | "tmj" | "tsj" | "json"; default: the source's flavour, else tmx
encoding: string?, -- tile data: "csv" (TMX default) | "base64" | "xml" (TMX only); TMJ: arrays unless "base64"
compression: string?, -- base64 data: nil | "zlib" | "gzip"
level: number?, -- deflate level for compressed data (default 6)
indent: number?, -- spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON)
compression: string?, -- nil | "zlib" | "gzip"
level: number?, -- default 6
indent: number?, -- default 1 (TMX), 2 (TMJ); 0 = compact JSON
}
-- ------------------------------------------------------------------------------------------------ sniff
@@ -72,8 +65,6 @@ function Tiled.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
-- decode(r, opts?) -> TileMap (or, for a .tsx / .tsj file, a TileMap with that one tileset and no layers; its
-- meta.tileset is true) | nil, Err
function Tiled.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.TileMap?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if r.limit - r.base > maxBytes then