comments: core/Bytes + compat/luajit down to specs and quirks

This commit is contained in:
4DBug committed 2026-11-01 01:57:14 -05:00
1 parent 5c42fae954
commit f3daec0744
2 files changed
+12 -83

No files matched your search

+11 -40
View File
@@ -1,20 +1,8 @@
-- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain luajit and LÖVE).
-- tools/build.py copies this file to build/luajit/rosetta/_compat.lua, and every built module starts with
-- local __compat = require("rosetta._compat") local buffer, bit32, utf8, typeof, type, __iter = ...
-- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string
-- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing.
--
-- Semantics follow Luau (checked by tests/compat.luau under both runtimes):
-- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap
-- (fractional operands: see the bit32 section).
-- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws
-- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a
-- private metatable: typeof(b) and the injected type(b) return "buffer".
-- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to
-- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the
-- table has no keys past #t, anything else with next.
-- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b
-- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes.
-- compat/luajit.lua: the Luau standard library pieces rosetta uses, for LuaJIT 2.1 (plain and LÖVE), with Luau
-- semantics (tests/compat.luau). tools/build.py prepends `local __compat = require("rosetta._compat") ...` to every
-- built module's first line. Nothing is installed globally; table / math / string additions only fill gaps.
-- buffer = { p = uint8_t*, n = length } with a private metatable (typeof / type say "buffer"); LuaJIT-only
-- buffer.toffi(b) / buffer.fromffi(ptr, n).
local ffi = require("ffi")
local bit = require("bit")
local floor = math.floor
@@ -24,17 +12,13 @@ local TWO32 = 4294967296
local M = {}
-- ---------------------------------------------------------------------------------------------------- bit32
-- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32.
-- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs
-- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step).
-- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never
-- passes fractions to bit32 (tests/compat.luau checks integers only).
-- The inline `if r < 0 then r = r + 2^32 end` sign fix runs ~45% faster than `r % 2^32` (inflate).
-- Divergence: bit.tobit rounds a fractional operand where Luau truncates (the library never passes fractions).
do
local band, bor, bxor, bnot, lshift, rshift, arshift, bswap =
bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap
local B = {}
-- the 2- and 3-argument forms are the hot ones: no varargs on that path
function B.band(a, b, c, d, ...)
local r
if b == nil then
@@ -185,7 +169,6 @@ do
M.bit32 = B
end
-- ---------------------------------------------------------------------------------------------------- buffer
do
ffi.cdef([[
void *memmove(void *dst, const void *src, size_t n);
@@ -207,9 +190,8 @@ do
BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end
M.BUFFER_MT = BUF
-- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the
-- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every
-- 512 MB of them.
-- big buffers are calloc'd so they don't count against the 2 GB GC heap of non-GC64 builds (LÖVE); a full
-- collection runs every 512 MB of them since the GC doesn't see those bytes
local BIG = 262144
local external = 0
@@ -379,7 +361,6 @@ do
end
end
-- LuaJIT-only extensions
function Buf.toffi(b) return b.p end
function Buf.fromffi(ptr, n)
local b = create(n)
@@ -389,7 +370,6 @@ do
M.buffer = Buf
end
-- ---------------------------------------------------------------------------------------------------- typeof / type
do
local BUF = M.BUFFER_MT
function M.type(v)
@@ -403,7 +383,6 @@ do
M.isbuffer = function(v) return getmetatable(v) == BUF end
end
-- ---------------------------------------------------------------------------------------------------- __iter
local function arrayIter(s, i)
local t, n = s[1], s[2]
i = i + 1
@@ -429,7 +408,6 @@ function M.__iter(t, s, c)
return next, t, nil
end
-- ---------------------------------------------------------------------------------------------------- table
do
local okn, tnew = pcall(require, "table.new")
local okc, tclear = pcall(require, "table.clear")
@@ -474,11 +452,9 @@ do
end
end
-- ---------------------------------------------------------------------------------------------------- math
do
-- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent
-- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and
-- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo).
-- math.min / math.max are branch-free in a trace; an if / elseif clamp spawned side traces and ran ~3.5x slower.
-- NaN stays NaN, as in Luau (maxsd would return lo).
local mmin, mmax = math.min, math.max
math.clamp = math.clamp or function(x, lo, hi)
if lo > hi then error("max must be greater than or equal to min", 2) end
@@ -506,7 +482,6 @@ do
end
end
-- ---------------------------------------------------------------------------------------------------- string
string.split = string.split or function(s, sep)
sep = sep or ","
local out = {}
@@ -526,7 +501,6 @@ string.split = string.split or function(s, sep)
end
end
-- ---------------------------------------------------------------------------------------------------- utf8
do
-- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it
local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" }
@@ -545,7 +519,6 @@ do
for i = 1, n do out[i] = enc((select(i, ...))) end
return table.concat(out)
end
-- decode at byte i: codepoint, length; nil on invalid UTF-8
local function dec(s, i)
local c = byte(s, i)
if not c then return nil end
@@ -592,7 +565,6 @@ do
end
return unpack(out, 1, k)
end
-- len(s, i, j) -> count | nil, position of the first invalid byte
function U.len(s, i, j)
i = i or 1
j = j or #s
@@ -643,7 +615,6 @@ do
M.utf8 = utf8 or U
end
-- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself)
function M.install(env)
env = env or _G
env.buffer = env.buffer or M.buffer
+1 -43
View File
@@ -2,19 +2,8 @@
--!native
-- core/Bytes: a cursor Reader over a buffer range and a growable Writer. Little / big endian integers up to u64 (as a
-- double: exact to 2^53), f16 / f32 / f64, C strings, fixed strings, and zero-copy sub-readers.
--
-- Never throws. A read past the end (or a failed seek) sets the reader's sticky `err` (Err.TRUNCATED), moves the cursor
-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads:
--
-- local r = Bytes.reader(buf) -- or Bytes.reader(buf, offset, length)
-- local magic, w, h = r:string(4), r:u32be(), r:u32be()
-- if r.err then return nil, r.err end
-- if magic ~= "abcd" then return r:fail(Err.CORRUPT, "bad magic") end
--
-- local w = Bytes.writer() -- or Bytes.writer(initialCapacity)
-- w:string("abcd"); w:u32be(width); local out = w:finish()
--
-- local b, o, n, err = Bytes.span("Deflate.inflate", input, offset?, length?) -- codec argument checking
-- to the end and returns 0 / "" (a zero-length buffer for bytes()); check `r.err` once after a run of reads.
local Err = require("@rosetta/core/Err")
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
@@ -28,7 +17,6 @@ local scratch = bcreate(8) -- reinterpret casts for big-endian floats
local Bytes = {}
-- ------------------------------------------------------------------------------------------------ Reader
local Reader = {}
Reader.__index = Reader
@@ -43,7 +31,6 @@ export type Reader = typeof(setmetatable(
Reader
))
-- reader(buf, offset?, length?) -> Reader over buf[offset, offset + length), clamped to the buffer
function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
local n = blen(buf)
local o = math.clamp(offset or 0, 0, n)
@@ -51,7 +38,6 @@ function Bytes.reader(buf: buffer, offset: number?, length: number?): Reader
return setmetatable({ buf = buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- fail(code, message) -> nil, Err: records the first error (at the cursor) and returns it, for `return r:fail(...)`
function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err)
if not self.err then
self.err = Err.new(code, message, self.pos)
@@ -59,7 +45,6 @@ function Reader.fail(self: Reader, code: string, message: string): (nil, Err.Err
return nil, self.err :: Err.Err
end
-- need(n) -> true when n more bytes are available; otherwise records TRUNCATED and moves to the end
function Reader.need(self: Reader, n: number): boolean
if self.pos + n <= self.limit and n >= 0 then
return true
@@ -84,7 +69,6 @@ function Reader.eof(self: Reader): boolean
return self.pos >= self.limit
end
-- seek(offset) -> boolean: offset relative to the reader's start; out of range records TRUNCATED
function Reader.seek(self: Reader, offset: number): boolean
if offset < 0 or self.base + offset > self.limit then
self.pos = self.limit
@@ -105,7 +89,6 @@ function Reader.skip(self: Reader, n: number): boolean
return false
end
-- align(n): skip to the next multiple of n (relative to the reader's start)
function Reader.align(self: Reader, n: number): boolean
local r = (self.pos - self.base) % n
if r == 0 then
@@ -114,7 +97,6 @@ function Reader.align(self: Reader, n: number): boolean
return self:skip(n - r)
end
-- integers
function Reader.u8(self: Reader): number
local p = self.pos
if p + 1 > self.limit then
@@ -213,7 +195,6 @@ function Reader.i32be(self: Reader): number
local v = self:u32be()
return if v >= 2147483648 then v - TWO32 else v
end
-- 64-bit integers as doubles (exact below 2^53)
function Reader.u64le(self: Reader): number
local lo = self:u32le()
return lo + self:u32le() * TWO32
@@ -231,7 +212,6 @@ function Reader.i64be(self: Reader): number
return hi * TWO32 + self:u32be()
end
-- floats
local function half(h: number): number
local s = if h >= 32768 then -1 else 1
local e = bit32.band(bit32.rshift(h, 10), 31)
@@ -282,7 +262,6 @@ function Reader.f64be(self: Reader): number
return readf64(scratch, 0)
end
-- strings
function Reader.string(self: Reader, n: number): string
local p = self.pos
if n < 0 or p + n > self.limit then
@@ -293,14 +272,12 @@ function Reader.string(self: Reader, n: number): string
return readstring(self.buf, p, n)
end
-- fixed(n): an n-byte field, cut at the first NUL
function Reader.fixed(self: Reader, n: number): string
local s = self:string(n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
-- cstring(max?): bytes up to a NUL (consumed, not returned); no NUL before the end (or max bytes) records TRUNCATED
function Reader.cstring(self: Reader, max: number?): string
local p = self.pos
local e = if max then math.min(self.limit, p + max) else self.limit
@@ -318,7 +295,6 @@ function Reader.cstring(self: Reader, max: number?): string
return readstring(buf, p, q - p)
end
-- match(s) -> true (and skips s) when the next bytes are s; otherwise false, nothing consumed, no error
function Reader.match(self: Reader, s: string): boolean
local p, n = self.pos, #s
if p + n > self.limit or readstring(self.buf, p, n) ~= s then
@@ -328,7 +304,6 @@ function Reader.match(self: Reader, s: string): boolean
return true
end
-- peek(n, at?) -> up to n bytes as a string at the cursor (+ at), without consuming; short at the end, never an error
function Reader.peek(self: Reader, n: number, at: number?): string
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
@@ -337,7 +312,6 @@ function Reader.peek(self: Reader, n: number, at: number?): string
return readstring(self.buf, p, math.min(n, self.limit - p))
end
-- peekU8(at?) -> the byte at the cursor (+ at), or -1 past the end
function Reader.peekU8(self: Reader, at: number?): number
local p = self.pos + (at or 0)
if p < self.base or p >= self.limit then
@@ -346,7 +320,6 @@ function Reader.peekU8(self: Reader, at: number?): number
return readu8(self.buf, p)
end
-- bytes(n) -> a new buffer with a copy of the next n bytes
function Reader.bytes(self: Reader, n: number): buffer
local p = self.pos
if n < 0 or p + n > self.limit then
@@ -359,8 +332,6 @@ function Reader.bytes(self: Reader, n: number): buffer
return b
end
-- slice(n) -> a Reader over the next n bytes (no copy); the parent skips them. Short data: a reader over what is
-- left, and the parent records TRUNCATED.
function Reader.slice(self: Reader, n: number): Reader
local p = self.pos
local l = math.max(0, math.min(n, self.limit - p))
@@ -372,15 +343,12 @@ function Reader.slice(self: Reader, n: number): Reader
return setmetatable({ buf = self.buf, pos = p, base = p, limit = p + l, err = nil :: Err.Err? }, Reader)
end
-- sub(offset, length?) -> a Reader over [offset, offset + length) relative to this reader's start (clamped), without
-- moving the cursor
function Reader.sub(self: Reader, offset: number, length: number?): Reader
local o = math.clamp(self.base + offset, self.base, self.limit)
local l = math.clamp(length or (self.limit - o), 0, self.limit - o)
return setmetatable({ buf = self.buf, pos = o, base = o, limit = o + l, err = nil :: Err.Err? }, Reader)
end
-- ------------------------------------------------------------------------------------------------ Writer
local Writer = {}
Writer.__index = Writer
@@ -392,12 +360,10 @@ export type Writer = typeof(setmetatable(
Writer
))
-- writer(capacity?) -> Writer
function Bytes.writer(capacity: number?): Writer
return setmetatable({ buf = bcreate(math.max(16, capacity or 256)), pos = 0 }, Writer)
end
-- reserve(n): make room for n more bytes; returns the write offset (for direct buffer.write* into w.buf)
function Writer.reserve(self: Writer, n: number): number
local p = self.pos
local cap = blen(self.buf)
@@ -493,12 +459,10 @@ function Writer.string(self: Writer, s: string)
writestring(self.buf, p, s)
self.pos = p + n
end
-- cstring(s): s and a NUL
function Writer.cstring(self: Writer, s: string)
self:string(s)
self:u8(0)
end
-- bytes(b, offset?, length?): copy a buffer range
function Writer.bytes(self: Writer, b: buffer, offset: number?, length: number?)
local o = offset or 0
local n = length or (blen(b) - o)
@@ -512,7 +476,6 @@ function Writer.fill(self: Writer, v: number, n: number)
self.pos = p + n
end
-- patch fields written earlier (lengths, CRCs) at an absolute offset < pos
function Writer.setU32le(self: Writer, at: number, v: number)
writeu32(self.buf, at, v)
end
@@ -526,7 +489,6 @@ function Writer.setU8(self: Writer, at: number, v: number)
writeu8(self.buf, at, v)
end
-- finish() -> a buffer of exactly the written bytes (the writer can keep going)
function Writer.finish(self: Writer): buffer
local b = bcreate(self.pos)
bcopy(b, 0, self.buf, 0, self.pos)
@@ -536,8 +498,6 @@ end
Bytes.Reader = Reader
Bytes.Writer = Writer
-- ------------------------------------------------------------------------------------------------ arguments
-- toBuffer(v) -> v as a buffer (strings are copied) | nil for anything else
function Bytes.toBuffer(v: any): buffer?
if type(v) == "string" then
return buffer.fromstring(v)
@@ -545,8 +505,6 @@ function Bytes.toBuffer(v: any): buffer?
return if type(v) == "buffer" then v else nil
end
-- span(what, input, offset?, length?) -> buffer, offset, length | nil, 0, 0, Err.ARG: a codec's (buffer | string,
-- offset, length) arguments checked (whole numbers, offset inside the data; the length is clamped to the end)
function Bytes.span(what: string, input: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = Bytes.toBuffer(input)
if not b then