UNPKG

@thi.ng/soa

Version:

SOA & AOS memory mapped structured views with optional & extensible serialization

56 lines (55 loc) 1.14 kB
import { identity } from "@thi.ng/api/fn"; import { assert } from "@thi.ng/errors/assert"; import { utf8Decode, utf8Encode } from "@thi.ng/transducers-binary/utf8"; const ident = { decode: identity, encode: identity }; const scalar = { decode: (v) => v[0], encode: (x) => [x] }; const __toUTF8 = utf8Decode(); const utf8z = (maxLen) => ({ decode: (v) => { let acc = ""; const xf = __toUTF8([ null, null, (_, x) => acc += x ])[2]; for (let i = 0, n = v.length; i < n; i++) { const c = v[i]; if (c === 0) break; xf(acc, c); } return acc; }, encode: (v) => { const bytes = [...utf8Encode(v), 0]; assert(bytes.length <= maxLen, `string too large: "${v}"`); return bytes; } }); const serializer = (specs) => ({ decode(tuple) { const res = {}; for (const id in tuple) { res[id] = specs[id].decode(tuple[id]); } return res; }, encode: (tuple) => { const res = {}; for (const id in tuple) { res[id] = specs[id].encode(tuple[id]); } return res; } }); export { ident, scalar, serializer, utf8z };