/
serializable-bitmasks.ts
267 lines (245 loc) · 7.94 KB
/
serializable-bitmasks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import {DeserializeOptions, SerializeOptions} from './serializable';
import {getJsonFieldSettings} from './serializable-objects-internal';
import {SerializableWrapper} from './serializable-wrapper';
import {toJSON} from './utils';
/** A numeric value that represents a bitmask of several fields.*/
export abstract class SBitmask extends SerializableWrapper<number> {
/** Create a new instance of this wrapper class from a raw value. */
static of<SBitmaskT extends SBitmask>(
this: new () => SBitmaskT,
value: number
): SBitmaskT;
/** Returns an SBitmask class that serializes using the provided
* SerializableWrapper. */
static of(
wrapperType: new () => SerializableWrapper<number>
): ReturnType<typeof createSBitmaskClass>;
static of(arg: number | (new () => SerializableWrapper<number>)) {
if (typeof arg === 'number') {
return super.of(arg);
}
if (
typeof arg === 'function' &&
arg.prototype instanceof SerializableWrapper
) {
return createSBitmaskClass(arg);
}
throw new Error(
'SBitmask.of() should be invoked either with a number value ' +
'or a SerializableWrapper<number> constructor'
);
}
/** Create a new instance with the provided initial properties. */
static with<T extends SBitmask>(
this: new () => T,
props: Partial<T> = {}
): T {
const instance = new this();
Object.assign(instance, props);
return instance;
}
/** The SerializableWrapper class to use for serializing / deserializing. */
abstract wrapperType: new () => SerializableWrapper<number>;
get value() {
const bitfields = getSBitfieldSpecs(this);
const wrapper = new this.wrapperType();
validateLength(bitfields, wrapper.getSerializedLength());
wrapper.value = 0;
let offset = 0;
for (let i = bitfields.length - 1; i >= 0; --i) {
const {propertyKey, length} = bitfields[i];
const fieldMask = 2 ** length - 1;
// Checks the type of the property is valid.
getValueType(this, propertyKey);
wrapper.value |= (((this as any)[propertyKey] | 0) & fieldMask) << offset;
offset += length;
}
return wrapper.value;
}
set value(newValue: number) {
const bitfields = getSBitfieldSpecs(this);
validateLength(bitfields, new this.wrapperType().getSerializedLength());
let offset = 0;
for (let i = bitfields.length - 1; i >= 0; --i) {
const {propertyKey, length} = bitfields[i];
const fieldMask = 2 ** length - 1;
const valueType = getValueType(this, propertyKey);
(this as any)[propertyKey] = valueType((newValue >> offset) & fieldMask);
offset += length;
}
}
deserialize(buffer: Buffer, opts?: DeserializeOptions): number {
const wrapper = new this.wrapperType();
const readOffset = wrapper.deserialize(buffer, opts);
this.value = wrapper.value;
return readOffset;
}
serialize(opts?: SerializeOptions): Buffer {
const wrapper = new this.wrapperType();
wrapper.value = this.value;
return wrapper.serialize(opts);
}
getSerializedLength(opts?: SerializeOptions): number {
const wrapper = new this.wrapperType();
return wrapper.getSerializedLength(opts);
}
toJSON(): any {
const jsonFieldSettings = getJsonFieldSettings(this);
jsonFieldSettings.excluded.add('wrapperType');
const result = Object.fromEntries(
Object.entries(this)
.filter(([propertyKey]) => !jsonFieldSettings.excluded.has(propertyKey))
.map(([propertyKey, value]) => [propertyKey, toJSON(value)])
);
Object.assign(
result,
Object.fromEntries(
Array.from(jsonFieldSettings.included)
.filter((propertyKey) => !(propertyKey in result))
.map((propertyKey) => [
propertyKey,
toJSON((this as any)[propertyKey]),
])
)
);
return result;
}
assignJSON(jsonValue: number | {[key: string | symbol]: number}): void {
if (typeof jsonValue === 'number') {
this.value = jsonValue;
} else if (typeof jsonValue === 'object') {
Object.assign(this, jsonValue);
} else {
throw new Error(
'Expected a number or an object in SBitmask.assignJSON(), ' +
`but got ${typeof jsonValue}`
);
}
}
}
function createSBitmaskClass(
wrapperType: new () => SerializableWrapper<number>
) {
return class extends SBitmask {
wrapperType = wrapperType;
};
}
type BitfieldDecorator<ValueT> = {
(
value: Function,
context: ClassGetterDecoratorContext | ClassSetterDecoratorContext
): void;
(
value: undefined,
context: ClassFieldDecoratorContext
): (initialValue: ValueT) => ValueT;
};
/** Decorator for bitfields in an SBitmask. */
export function bitfield<ValueT extends number | boolean>(length: number) {
return function (
value: undefined | Function,
context:
| ClassFieldDecoratorContext
| ClassGetterDecoratorContext
| ClassSetterDecoratorContext
) {
context.addInitializer(function () {
registerBitfield(this, context.name, length);
});
switch (context.kind) {
case 'field':
return (initialValue: ValueT) => initialValue;
case 'getter':
case 'setter':
return;
default:
throw new Error('@bitfield() should only be used on class properties');
}
} as BitfieldDecorator<ValueT>;
}
/** Key for storing field information on an SBitmask's metadata. */
const SBITMASK_METADATA_KEY = Symbol('__sbitmaskMetadata');
/** Metadata stored for each field on an SBitmask's metadata. */
interface SBitfieldSpec {
/** The name of the field. */
propertyKey: string | symbol;
/** Number of bits associated with this field. */
length: number;
}
/** Metadata stored on an SBitmask's prototype. */
interface SBitmaskMetadata {
/** List of bitfields, in declaration order. */
fieldSpecs: Array<SBitfieldSpec>;
/** Name of all bitfields as a set. */
propertyKeys: Set<string | symbol>;
}
/** Registers a bitfield in the metadata of an SBitmask. */
function registerBitfield<ValueT>(
targetInstance: any,
propertyKey: string | symbol,
length: number
) {
const targetPrototype = Object.getPrototypeOf(targetInstance);
const metadata = targetPrototype[SBITMASK_METADATA_KEY] as
| SBitmaskMetadata
| undefined;
const fieldSpec: SBitfieldSpec = {
propertyKey,
length,
};
if (metadata) {
if (metadata.propertyKeys.has(propertyKey)) {
return;
}
metadata.propertyKeys.add(propertyKey);
metadata.fieldSpecs.push(fieldSpec);
} else {
const newMetadata: SBitmaskMetadata = {
fieldSpecs: [fieldSpec],
propertyKeys: new Set<string | symbol>([propertyKey]),
};
targetPrototype[SBITMASK_METADATA_KEY] = newMetadata;
}
}
/** Extract SBitfieldSpec's defined on a SObject. */
function getSBitfieldSpecs(targetInstance: any) {
return (
(
Object.getPrototypeOf(targetInstance)[SBITMASK_METADATA_KEY] as
| SBitmaskMetadata
| undefined
)?.fieldSpecs ?? []
);
}
/** Checks that the total length of bitfields matches the value wrapper length. */
function validateLength(
bitfields: Array<SBitfieldSpec>,
expectedLength: number
) {
const expectedBitLength = expectedLength * 8;
const totalBitLength = bitfields
.map(({length}) => length)
.reduce((a, b) => a + b, 0);
if (totalBitLength !== expectedBitLength) {
throw new Error(
'Total length of bitfields do not match bitmask length: ' +
`expected ${expectedBitLength} bits, ` +
`but total length of bitfields is ${totalBitLength} bits`
);
}
}
/** Returns the constructor for a bitfield value. */
function getValueType(targetInstance: any, propertyKey: string | symbol) {
const value = targetInstance[propertyKey];
switch (typeof value) {
case 'number':
return Number;
case 'boolean':
return Boolean;
default:
throw new Error(
`Expected property ${propertyKey.toString()} to be a number or boolean, ` +
`but it is ${typeof value}`
);
}
}