typia
Version:
Superfast runtime validators with only one line
94 lines (93 loc) • 2.15 kB
JavaScript
import { Singleton } from "@typia/utils";
//#region src/internal/_ProtobufWriter.ts
var _ProtobufWriter = class {
constructor(sizer) {
this.sizer = sizer;
this.buf = new Uint8Array(sizer.len);
this.view = new DataView(this.buf.buffer);
this.ptr = 0;
this.varlenidx = 0;
}
buffer() {
return this.buf;
}
bool(value) {
this.byte(value ? 1 : 0);
}
byte(value) {
this.buf[this.ptr++] = value & 255;
}
int32(value) {
if (value < 0) this.int64(value);
else this.variant32(value >>> 0);
}
sint32(value) {
this.variant32(value << 1 ^ value >> 31);
}
uint32(value) {
this.variant32(value);
}
sint64(value) {
value = BigInt(value);
this.variant64(value << BigInt(1) ^ value >> BigInt(63));
}
int64(value) {
this.variant64(BigInt(value));
}
uint64(value) {
this.variant64(BigInt(value));
}
float(val) {
this.view.setFloat32(this.ptr, val, true);
this.ptr += 4;
}
double(val) {
this.view.setFloat64(this.ptr, val, true);
this.ptr += 8;
}
bytes(value) {
this.uint32(value.byteLength);
for (let i = 0; i < value.byteLength; i++) this.buf[this.ptr++] = value[i];
}
string(value) {
const len = this.varlen();
this.uint32(len);
const binary = utf8.get().encode(value);
for (let i = 0; i < binary.byteLength; i++) this.buf[this.ptr++] = binary[i];
}
fork() {
this.uint32(this.varlen());
}
ldelim() {}
finish() {
return this.buf;
}
reset() {
this.buf = new Uint8Array(this.sizer.len);
this.view = new DataView(this.buf.buffer);
this.ptr = 0;
this.varlenidx = 0;
}
variant32(val) {
while (val > 127) {
this.buf[this.ptr++] = val & 127 | 128;
val = val >>> 7;
}
this.buf[this.ptr++] = val;
}
variant64(val) {
val = BigInt.asUintN(64, val);
while (val > BigInt(127)) {
this.buf[this.ptr++] = Number(val & BigInt(127) | BigInt(128));
val = val >> BigInt(7);
}
this.buf[this.ptr++] = Number(val);
}
varlen() {
return this.varlenidx >= this.sizer.varlen.length ? 0 : this.sizer.varlen[this.varlenidx++];
}
};
const utf8 = new Singleton(() => new TextEncoder());
//#endregion
export { _ProtobufWriter };
//# sourceMappingURL=_ProtobufWriter.mjs.map