Files
rosetta/src/Formats/font/woff2/init.luau
T

60 lines
2.4 KiB
Luau

--!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/TrueType (TrueType or CFF
-- outlines, see font/ttf). Written from the spec; Brotli is codecs/Brotli. Not supported: collections, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local TrueType = require("@formats/codecs/TrueType")
local Rebuild = require("@formats/font/woff2/Rebuild")
-- ------------------------------------------------------------------------------------------------ contract
local Woff2 = {
name = "woff2",
category = "font",
extensions = { "woff2" },
mime = { "font/woff2" },
deps = { "core/Err", "core/Bytes", "codecs/TrueType", "codecs/Brotli" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, transforms = { "glyf", "loca", "hmtx" } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODES = { truncated = Err.TRUNCATED, corrupt = Err.CORRUPT, unsupported = Err.UNSUPPORTED, limit = Err.LIMIT }
-- ------------------------------------------------------------------------------------------------ sniff
function Woff2.sniff(r: Bytes.Reader): number
return if r:peek(4) == "wOF2" then 1 else 0
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
local out, msg, code = Rebuild.sfnt(r, maxBytes)
if not out then
return nil, Err.new(CODES[code or "corrupt"] or Err.CORRUPT, msg or "rebuild failed", at)
end
return out, nil
end
function Woff2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local sfnt, err = Woff2.sfnt(r, opts)
if not sfnt then
return nil, err
end
local font, ferr = TrueType.font(sfnt)
if not font then
return nil, ferr
end
font.meta.source = { format = "woff2", outlines = font.meta.outlines }
return font, nil
end
return Woff2