feat(Struct)

This commit is contained in:
2025-08-03 23:18:27 +03:00
parent 72f287a4e4
commit 38f0d922aa
15 changed files with 410 additions and 150 deletions

47
src/ConstArray.js Normal file
View File

@ -0,0 +1,47 @@
import { limits, parse, serialize, sizeofHead, Type } from "."
export function ConstArray(size) {
const obj = { _size: size }
Object.setPrototypeOf(obj, ConstArray.prototype)
obj.new(ConstArray, arguments)
return obj
}
ConstArray.prototype.serialize = function(dv, src, ...inner_types) {
const item_size = sizeofHead(src[0])
let size = this._size
if (dv.byteLength < size * item_size) {
throw new Error('too small buffer')
}
if (size > limits.u32.MAX_VALUE) {
throw new Error('array is too long')
}
dv.setUint32(0, size)
for (let i = 0; i < size; i++) {
const item_frame = new DataView(dv.buffer, dv.byteOffset + item_size * i)
serialize(item_frame, src[i], ...inner_types)
}
return
}
ConstArray.prototype.parse = function(dv, ...inner_types) {
const size = this._size
const item_size = sizeofHead(...inner_types)
const array = Array(size)
for (let i = 0; i < size; i++) {
const item_frame = new DataView(dv.buffer, dv.byteOffset + item_size * i)
array[i] = parse(item_frame, ...inner_types)
}
return array
}
ConstArray.prototype.isHeadless = function() {
return false
}
ConstArray.prototype.sizeof = function(...inner_types) {
return sizeofHead(...inner_types) * this._size
}
Object.setPrototypeOf(ConstArray.prototype, Type.prototype)
Object.freeze(ConstArray.prototype)