feat(Int)

This commit is contained in:
2025-08-05 10:09:53 +03:00
parent 8c2d7118c2
commit f5b485d546
5 changed files with 123 additions and 2 deletions

87
src/Int.js Normal file
View File

@ -0,0 +1,87 @@
import { Type, limits } from '.'
export function Int(bits, sign) {
const obj = { _size: bits / 8 }
Object.setPrototypeOf(obj, Int.prototype)
obj.new(Int, arguments)
switch (sign) {
case 'signed':
switch (bits) {
case 8:
obj._dv_set = DataView.prototype.setInt8
obj._dv_get = DataView.prototype.getInt8
obj._limits = limits.i8
break
case 16:
obj._dv_set = DataView.prototype.setInt16
obj._dv_get = DataView.prototype.getInt16
obj._limits = limits.i16
break
case 32:
obj._dv_set = DataView.prototype.setInt32
obj._dv_get = DataView.prototype.getInt32
obj._limits = limits.i32
break
default:
throw new Error('incorrect bits ' + bits)
}
break
case 'unsigned':
switch (bits) {
case 8:
obj._dv_set = DataView.prototype.setUint8
obj._dv_get = DataView.prototype.getUint8
obj._limits = limits.u8
break
case 16:
obj._dv_set = DataView.prototype.setUint16
obj._dv_get = DataView.prototype.getUint16
obj._limits = limits.u16
break
case 32:
obj._dv_set = DataView.prototype.setUint32
obj._dv_get = DataView.prototype.getUint32
obj._limits = limits.u32
break
default:
throw new Error('incorrect bits ' + bits)
}
break
default:
throw new Error('incorrect sign ' + sign)
}
return obj
}
Int.prototype.serialize = function (dv, src) {
if (dv.byteLength < this._size) {
throw new Error('buffer is too small')
}
if (src > this._limits.MAX_VALUE) {
throw new Error(`number should be less or equal than ` + this._limits.MAX_VALUE)
}
if (src < this._limits.MIN_VALUE) {
throw new Error(`number should be more or equal than ` + this._limits.MIN_VALUE)
}
this._dv_set.call(dv, 0, src)
}
Int.prototype.parse = function (dv) {
return this._dv_get.call(dv, 0)
}
Int.prototype.isHeadless = function () {
return false
}
Int.prototype.sizeof = function () {
return this._size
}
Object.setPrototypeOf(Int.prototype, Type.prototype)
Object.freeze(Int.prototype)

View File

@ -1,12 +1,13 @@
import { limits } from "./limits"
import { memcpy } from "./mem"
import { Type } from "./Type"
import { Int } from "./Int"
import { ConstString } from './ConstString'
import { ConstArray } from "./ConstArray"
import { ConstDataView } from './ConstDataView'
import { Struct } from './Struct'
export { limits, memcpy, Type, ConstString, ConstArray, ConstDataView, Struct }
export { limits, memcpy, Type, Int, ConstString, ConstArray, ConstDataView, Struct }
export function serialize(dv, src, ...types) {
const [type, ...inner_types] = types