Files
serialize-js/src/ConstString.js
2025-08-06 16:22:19 +03:00

37 lines
1.1 KiB
JavaScript

import { memcpy } from './mem'
import { Type } from './Type'
export function ConstString(size) {
const obj = { _size: size }
Object.setPrototypeOf(obj, ConstString.prototype)
obj.new(ConstString, arguments)
return obj
}
ConstString.prototype.serialize = function (dv, src) {
const encoder = new TextEncoder('utf-8')
const encoded = new DataView(encoder.encode(src).buffer, 0, this._size)
if (dv.byteLength < encoded.byteLength) {
throw new Error(this._name + ' too small buffer')
}
if (src.length != this._size) {
throw new Error(this._name + ' should be ' + this._size + ' symbols length')
}
memcpy(dv, encoded)
return
}
ConstString.prototype.parse = function (dv) {
const frame = new DataView(dv.buffer, dv.byteOffset, this._size)
const decoder = new TextDecoder('utf-8')
return decoder.decode(frame)
}
ConstString.prototype.isHeadless = function () {
return false
}
ConstString.prototype.sizeof = function () {
return this._size
}
Object.setPrototypeOf(ConstString.prototype, Type.prototype)
Object.freeze(ConstString.prototype)