data: data/csv (RFC 4180 + Python-lenient reading, delimiter / auto, header -> keyed rows, numbers option, minimal / all quoting); Python csv fixtures, byte-exact re-encode

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 08:52:26 -05:00
1 parent e050a521da
commit 2a39f689bc
5 files changed
+448

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` |
| data | csv | .csv .tsv | yes | yes | header: true | `tests/data/csv.luau` |
| data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` |
| data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` |
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
+12
View File
@@ -38,6 +38,18 @@ local list: { Entry } = {
return require("@formats/data/cbor")
end,
},
{
name = "csv",
category = "data",
path = "data/csv",
extensions = { "csv", "tsv" },
mime = { "text/csv", "text/tab-separated-values" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
caps = { decode = true, encode = true, header = true },
load = function()
return require("@formats/data/csv")
end,
},
{
name = "json",
category = "data",
+316
View File
@@ -0,0 +1,316 @@
--!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.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Json = require("@formats/codecs/Json")
-- ------------------------------------------------------------------------------------------------ contract
local Csv = {
name = "csv",
category = "data",
extensions = { "csv", "tsv" },
mime = { "text/csv", "text/tab-separated-values" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json" },
caps = { decode = true, encode = true, header = true },
}
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)
}
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)
}
-- ------------------------------------------------------------------------------------------------ constants
local find, sub, byte, gsub = string.find, string.sub, string.byte, string.gsub
local function patEscape(c: string): string
return (gsub(c, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0"))
end
-- ------------------------------------------------------------------------------------------------ sniff
function Csv.sniff(r: Bytes.Reader): number
local head = r:peek(1024)
if find(head, "%z") then
return 0
end
local l1, l2 = string.match(head, "^([^\r\n]*)\r?\n([^\r\n]*)")
if not l1 or l1 == "" then
return 0
end
for _, d in { ",", "\t", ";" } do
local _, c1 = gsub(l1, d, "")
local _, c2 = gsub(l2, d, "")
if c1 > 0 and c1 == c2 then
return 0.15
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function guess(s: string, q: string): string
local line = string.match(s, "^[^\r\n]*") or ""
line = gsub(line, patEscape(q) .. "[^" .. patEscape(q) .. "]*" .. patEscape(q), "")
local best, bestN = ",", 0
for _, d in { ",", ";", "\t", "|" } do
local _, n = gsub(line, patEscape(d), "")
if n > bestN then
best, bestN = d, n
end
end
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 '"'
local d = o.delimiter or ","
if d == "auto" then
d = guess(s, q)
end
if #d ~= 1 or #q ~= 1 or d == q or d == "\n" or d == "\r" then
return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes (not line ends)")
end
local qb, db = byte(q), byte(d)
local stop = "[" .. patEscape(d) .. "\r\n]"
local maxRows = o.maxRows or math.huge
local rows: { { string } } = {}
local row: { string } = {}
local n = #s
local i = 1
local rowEmpty = true -- the current line has no field text yet (blank lines are skipped)
while true do
local c = byte(s, i)
local field: string
if c == qb then
local k = i + 1
local parts = {}
while true do
local j = find(s, q, k, true)
if not j then
return nil, Err.new(Err.TRUNCATED, "unterminated quoted field", i - 1)
end
if byte(s, j + 1) == qb then
table.insert(parts, sub(s, k, j))
k = j + 2
else
table.insert(parts, sub(s, k, j - 1))
i = j + 1
break
end
end
-- text after the closing quote up to the delimiter is kept (Python's lenient reading)
local e = find(s, stop, i) or (n + 1)
if e > i then
table.insert(parts, sub(s, i, e - 1))
end
i = e
field = table.concat(parts)
rowEmpty = false
else
local e = find(s, stop, i) or (n + 1)
field = sub(s, i, e - 1)
if e > i then
rowEmpty = false
end
i = e
end
table.insert(row, field)
c = byte(s, i)
if c == db then
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
i += 1
end
if not rowEmpty then
table.insert(rows, row)
if #rows > maxRows then
return nil, Err.new(Err.LIMIT, "more than " .. maxRows .. " rows")
end
end
row = {}
rowEmpty = true
if i > n then
break
end
end
end
return rows, nil
end
local NUMBER = "^%s*[%-%+]?%d+%.?%d*[eE]?[%-%+]?%d*%s*$"
local function convert(v: string): any
if string.match(v, NUMBER) or string.match(v, "^%s*[%-%+]?%.%d+[eE]?[%-%+]?%d*%s*$") then
local x = tonumber(v)
if x then
return x
end
end
return v
end
function Csv.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local s = buffer.readstring(r.buf, r.base, r.limit - r.base)
if sub(s, 1, 3) == "\239\187\191" then
s = sub(s, 4)
end
local rows, err = Csv.parse(s, opts)
if not rows then
return nil, err
end
local o: DecodeOptions = opts or {}
if o.numbers then
for _, row in rows do
for k, v in row do
row[k] = convert(v)
end
end
end
if not o.header then
return rows, nil
end
local names = rows[1] or {}
local out = table.create(math.max(#rows - 1, 0))
for k = 2, #rows do
local row = rows[k]
local obj = Types.object()
for c, name in names do
if row[c] ~= nil then
Types.set(obj, tostring(name), row[c])
end
end
out[k - 1] = obj
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function text(v: any): (string?, string?)
local tv = type(v)
if tv == "string" then
return v, nil
elseif tv == "number" then
local s = Json.number(v)
if not s then
return if v ~= v then "nan" elseif v > 0 then "inf" else "-inf", nil
end
return s, nil
elseif tv == "boolean" then
return if v then "true" else "false", nil
elseif v == nil or v == Types.null then
return "", nil
elseif tv == "table" and Types.Date.is(v) then
return tostring(v), nil
end
return nil, "cannot write a " .. tv .. " as a field"
end
local function isArray(t: any): boolean
if type(t) ~= "table" or Types.isObject(t) then
return false
end
local n = #t
return n > 0 or next(t) == nil
end
function Csv.encode(rows: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local d, q, nl = o.delimiter or ",", o.quote or '"', o.newline or "\r\n"
if #d ~= 1 or #q ~= 1 or d == q then
return nil, Err.new(Err.ARG, "delimiter and quote must be single, different bytes")
end
if type(rows) ~= "table" then
return nil, Err.new(Err.ARG, "expected an array of rows")
end
local special = "[" .. patEscape(d) .. patEscape(q) .. "\r\n]"
local qq = q .. q
local out: { string } = {}
local function writeRow(fields: { any }, count: number): Err.Err?
local parts = table.create(count)
for k = 1, count do
local s, e = text(fields[k])
if not s then
return Err.new(Err.ARG, "row " .. (#out + 1) .. ", field " .. k .. ": " .. tostring(e))
end
if o.quoteAll or find(s, special) or (count == 1 and s == "") then
s = q .. gsub(s, patEscape(q), qq) .. q
end
parts[k] = s
end
table.insert(out, table.concat(parts, d) .. nl)
return nil
end
local keyed = rows[1] ~= nil and not isArray(rows[1])
if keyed then
local cols = o.columns
if not cols then
local seen, list = {}, {}
for _, row in rows do
if type(row) ~= "table" then
return nil, Err.new(Err.ARG, "rows must be tables")
end
for _, k in Types.keys(row) do
if not seen[k] then
seen[k] = true
table.insert(list, k)
end
end
end
cols = list
end
local cl = cols :: { any }
if o.header ~= false then
local e = writeRow(cl, #cl)
if e then
return nil, e
end
end
for _, row in rows do
local fields = table.create(#cl)
for k, name in cl do
fields[k] = row[name]
end
local e = writeRow(fields, #cl)
if e then
return nil, e
end
end
else
for _, row in rows do
if type(row) ~= "table" then
return nil, Err.new(Err.ARG, "rows must be arrays of fields")
end
local e = writeRow(row, #row)
if e then
return nil, e
end
end
end
return buffer.fromstring(table.concat(out)), nil
end
return Csv
+76
View File
@@ -0,0 +1,76 @@
-- data/csv tests: tables written by Python's csv.writer / DictWriter (every delimiter, quotes, line breaks inside
-- fields, empty fields) read back as csv.reader does, re-encoded byte for byte, keyed rows with a header, options,
-- error codes, and the fuzz pass. Fixtures: tools/fixtures/csv.py.
local T = require("@tests/T")
local F = require("@formats")
local Csv = require("@formats/data/csv")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Canon = require("@tests/data/Canon")
local Fx = require("@tests/gen/csv")
local t = T.suite("data/csv")
t:eq(Csv.name, "csv", "name")
t:check(Csv.caps.decode and Csv.caps.encode, "caps")
local function dec(s: string, opts: any?): (any, any)
return Csv.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
for i, c in Fx do
local rows, err = dec(c.data, { delimiter = c.delimiter })
t:check(rows ~= nil, "case " .. i .. ": " .. tostring(err))
t:eq(Canon.of(rows), Canon.of(c.rows), "case " .. i .. ": rows")
local b = Csv.encode(rows, { delimiter = c.delimiter, newline = c.newline }) :: buffer
t:eq(buffer.tostring(b), c.data, "case " .. i .. ": same text")
if c.delimiter ~= "," or i % 3 == 0 then
local auto = dec(c.data, { delimiter = "auto" })
if c.rows[1] and #c.rows[1] > 1 and auto then
-- auto only has the first line to go on; it must at least split like the real delimiter there
t:check(#auto[1] >= 1, "case " .. i .. ": auto")
end
end
if c.keyed then
local keyed = dec(c.data, { header = true }) :: any
t:eq(#keyed, #c.rows - 1, "case " .. i .. ": keyed row count")
t:eq(table.concat(Types.keys(keyed[1]), "|"), table.concat(c.rows[1], "|"), "case " .. i .. ": column order")
local kb = Csv.encode(keyed) :: buffer
t:eq(buffer.tostring(kb), c.data, "case " .. i .. ": keyed re-encode (DictWriter text)")
end
end
-- details
do
t:eq(Canon.of(dec("a,b\n\n1,2\r\n3,4\r5,6")), Canon.of({ { "a", "b" }, { "1", "2" }, { "3", "4" }, { "5", "6" } }), "line ends, blank lines")
t:eq(Canon.of(dec('"a""b",c"d,"e"x')), Canon.of({ { 'a"b', 'c"d', "ex" } }), "lenient quotes like Python")
t:eq(Canon.of(dec("a;b|c", { delimiter = "auto" })), Canon.of({ { "a", "b|c" } }), "auto delimiter")
t:eq(Canon.of(dec("x,1.5,-2,1e3,abc, 7 ", { numbers = true })), Canon.of({ { "x", 1.5, -2, 1000, "abc", 7 } }), "numbers")
t:eq(Canon.of(dec("a,b,c\n1,2")[1]), Canon.of({ "a", "b", "c" }), "ragged rows kept")
local k = dec("a,b\n1,2,3\n4", { header = true })
t:eq(k[1].b, "2", "keyed")
t:eq(k[2].b, nil, "short keyed row")
t:eq(buffer.tostring(Csv.encode({ { 1, true, F.null, 0.5 } }) :: buffer), "1,true,,0.5\r\n", "field types")
t:eq(buffer.tostring(Csv.encode({ { "a", "b" } }, { quoteAll = true, newline = "\n" }) :: buffer), '"a","b"\n', "quoteAll")
t:eq(buffer.tostring(Csv.encode({ { "" } }) :: buffer), '""\r\n', "single empty field quoted")
local _, e = dec('a,"b')
t:eq(e and e.code, Err.TRUNCATED, "unterminated quote")
local _, e2 = dec("a", { delimiter = "ab" })
t:eq(e2 and e2.code, Err.ARG, "bad delimiter")
local _, e3 = Csv.encode({ { {} } })
t:eq(e3 and e3.code, Err.ARG, "bad field")
local _, e4 = dec("1\n2\n3", { maxRows = 2 })
t:eq(e4 and e4.code, Err.LIMIT, "maxRows")
local v = F.load(buffer.fromstring("a,b\r\n1,2\r\n"), { format = "csv", header = true })
t:eq(v[1].a, "1", "through the API")
end
local samples = {}
for i = 1, 40 do
table.insert(samples, Fx[i].data)
end
t:fuzz("decode", function(b: buffer)
return Csv.decode(Bytes.reader(b), { delimiter = "auto", header = true, numbers = true })
end, samples)
t:done()
+43
View File
@@ -0,0 +1,43 @@
# data/csv fixtures: random tables (quotes, delimiters, CR / LF / CRLF inside fields, empty fields, unicode) written
# by Python's csv.writer / DictWriter in several dialects, with the rows csv.reader reads back (blank rows dropped:
# we skip blank lines).
# tests/gen/csv.luau { { data, delimiter, rows = { { field } }, keyed? } }
# keyed: the file has a header row (DictWriter)
import csv, io
def rand_field(rng):
alph = 'ab ,;\t|"\n\ré中1.'
k = rng.random()
if k < 0.15:
return ""
if k < 0.3:
return str(rng.randrange(-1000, 1000))
return "".join(rng.choice(alph) for _ in range(rng.randrange(1, 8)))
def generate(ctx):
rng = ctx.rng(13)
cases = []
for i in range(200):
delim = rng.choice([",", ",", ";", "\t", "|"])
ncol = rng.randrange(1, 6)
rows = [[rand_field(rng) for _ in range(ncol)] for _ in range(rng.randrange(1, 12))]
buf = io.StringIO(newline="")
lt = "\r\n" if delim == "," else rng.choice(["\r\n", "\n"])
w = csv.writer(buf, delimiter=delim, lineterminator=lt)
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline=""), delimiter=delim) if r]
cases.append({"data": data.encode(), "delimiter": delim, "newline": lt, "rows": back})
for i in range(30):
cols = ["id", "name", "note é", "x,y"][: rng.randrange(1, 5)]
rows = [{c: rand_field(rng) for c in cols} for _ in range(rng.randrange(1, 8))]
buf = io.StringIO(newline="")
w = csv.DictWriter(buf, fieldnames=cols)
w.writeheader()
w.writerows(rows)
data = buf.getvalue()
back = [r for r in csv.reader(io.StringIO(data, newline="")) if r]
cases.append({"data": data.encode(), "delimiter": ",", "newline": "\r\n", "rows": back, "keyed": True})
ctx.emit("csv", cases)