flatbuffers
61 строка · 2.4 Кб
1import { Builder } from './builder.js'
2import { BitWidth } from './bit-width.js'
3import { paddingSize, uwidth, fromByteWidth } from './bit-width-util.js'
4import { ValueType } from './value-type.js'
5import { isInline, packedType } from './value-type-util.js'
6
7export class StackValue {
8constructor(private builder: Builder, public type: ValueType, public width: number, public value: number | boolean | null = null, public offset: number = 0) {
9
10}
11
12elementWidth(size: number, index: number): BitWidth {
13if (isInline(this.type)) return this.width;
14for (let i = 0; i < 4; i++) {
15const width = 1 << i;
16const offsetLoc = size + paddingSize(size, width) + index * width;
17const offset = offsetLoc - this.offset;
18const bitWidth = uwidth(offset);
19if (1 << bitWidth === width) {
20return bitWidth;
21}
22}
23throw `Element is unknown. Size: ${size} at index: ${index}. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new`;
24}
25
26writeToBuffer(byteWidth: number): void {
27const newOffset = this.builder.computeOffset(byteWidth);
28if (this.type === ValueType.FLOAT) {
29if (this.width === BitWidth.WIDTH32) {
30this.builder.view.setFloat32(this.builder.offset, this.value as number, true);
31} else {
32this.builder.view.setFloat64(this.builder.offset, this.value as number, true);
33}
34} else if (this.type === ValueType.INT) {
35const bitWidth = fromByteWidth(byteWidth);
36this.builder.pushInt(this.value as number, bitWidth);
37} else if (this.type === ValueType.UINT) {
38const bitWidth = fromByteWidth(byteWidth);
39this.builder.pushUInt(this.value as number, bitWidth);
40} else if (this.type === ValueType.NULL) {
41this.builder.pushInt(0, this.width);
42} else if (this.type === ValueType.BOOL) {
43this.builder.pushInt(this.value ? 1 : 0, this.width);
44} else {
45throw `Unexpected type: ${this.type}. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new`
46}
47this.offset = newOffset;
48}
49
50storedWidth(width = BitWidth.WIDTH8): BitWidth {
51return isInline(this.type) ? Math.max(width, this.width) : this.width;
52}
53
54storedPackedType(width = BitWidth.WIDTH8): ValueType {
55return packedType(this.type, this.storedWidth(width));
56}
57
58isOffset(): boolean {
59return !isInline(this.type)
60}
61}