-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoson.ts
332 lines (314 loc) · 10.1 KB
/
oson.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// deno-lint-ignore-file no-explicit-any
// magic numbers for values
/** internal magic number representing undefined */
export const UNDEFINED_INDEX = -1 as const;
/** internal magic number representing an array hole */
export const ARRAY_HOLE_INDEX = -2 as const;
/** internal magic number representing NaN */
export const NAN_INDEX = -3 as const;
/** internal magic number representing Infinity */
export const POS_INF_INDEX = -4 as const;
/** internal magic number representing -Infinity */
export const NEG_INF_INDEX = -5 as const;
// magic numbers for oson list type labels
/** internal magic number labelling a bigint */
export const BIG_INT_LABEL = -6 as const;
/** union type of all internal magic numbers */
export type OsonMagic =
| typeof UNDEFINED_INDEX
| typeof ARRAY_HOLE_INDEX
| typeof NAN_INDEX
| typeof POS_INF_INDEX
| typeof NEG_INF_INDEX;
/** encoded Oson data */
export type Oson = OsonMagic | OsonValue[];
/** value inside encoded Oson data */
export type OsonValue = OsonPrimitive | OsonList;
/** primitive value inside encoded Oson data */
export type OsonPrimitive = string | number | boolean | null;
/** complex value inside encoded Oson data */
export type OsonList = OsonBigInt | OsonArray | OsonObject;
/** bigint encoded as Oson data */
export type OsonBigInt = [typeof BIG_INT_LABEL, string];
/** array encoded as Oson data */
export type OsonArray = number[];
/** object encoded as Oson data */
export type OsonObject = [label: string, ...values: number[]];
function isOsonObject(array: OsonList): array is OsonObject {
return typeof array[0] === "string";
}
function isOsonBigInt(array: OsonList): array is OsonBigInt {
return array[0] === BIG_INT_LABEL;
}
export * from "./constructors.ts";
import {
type ConstructorMap,
GLOBAL_CONSTRUCTOR_MAP,
PLAIN_OBJECT_LABEL,
} from "./constructors.ts";
/**
* Converts a value to string. This will preserve circular and repeated
* references as well as undefined, sparse arrays, bigint, and all classes
* instances defined by the constructor map.
*
* @param value The value to convert to string
* @param constructors The constructor map to use for class instances
* @returns The string containing the encoded value
*/
export function stringify<C = any>(
value: unknown = undefined,
constructors: ConstructorMap<C> = GLOBAL_CONSTRUCTOR_MAP,
): string {
return JSON.stringify(listify(value, constructors));
}
/**
* Converts a string created using `stringify` back to a value. This will
* restore circular and repeated references as well as undefined, sparse arrays,
* bigint, and all classes instances defined by the constructor map.
*
* @param text The string containing the encoded value
* @param constructors The constructor map to use for class instances
* @returns The parsed value
*/
export function parse<C = any>(
text: string,
constructors: ConstructorMap<C> = GLOBAL_CONSTRUCTOR_MAP,
): any {
return delistify(JSON.parse(text), constructors);
}
function toMagicNumber(value: unknown): OsonMagic | null {
if (value === undefined) return UNDEFINED_INDEX;
if (typeof value === "number") {
if (isNaN(value)) return NAN_INDEX;
if (!isFinite(value)) return value < 0 ? NEG_INF_INDEX : POS_INF_INDEX;
}
return null;
}
function fromMagicNumber(value: number): undefined | number | null {
switch (value) {
case UNDEFINED_INDEX:
return undefined;
case NAN_INDEX:
return NaN;
case NEG_INF_INDEX:
return -Infinity;
case POS_INF_INDEX:
return Infinity;
default:
return null;
}
}
const SPARSE_PROTO: number[] = [];
function sparse(len: number) {
if (SPARSE_PROTO.length < len) {
const old = SPARSE_PROTO.length;
SPARSE_PROTO.length = len;
SPARSE_PROTO.fill(ARRAY_HOLE_INDEX, old, len);
}
return SPARSE_PROTO.slice(0, len);
}
function fromObject(
value: object,
constructors: ConstructorMap,
): [string, unknown[]] {
// check if we have this instance registered
const constr = value.constructor;
if (typeof constr === "function") {
const label = constr.name;
const inst = constructors.get(label);
if (inst !== undefined) {
return [label, inst.from(value)];
}
}
// no instance found, fall back to normal object
const entries = Object.entries(value);
const cnt = entries.length;
const val: unknown[] = Array(cnt + cnt);
for (let i = 0; i < cnt; i++) {
const entry = entries[i];
const ii = i + i;
val[ii] = entry[0];
val[ii + 1] = entry[1];
}
return [PLAIN_OBJECT_LABEL, val];
}
function stubObject(label: string, constructors: ConstructorMap) {
// stub a plain object
if (label === PLAIN_OBJECT_LABEL) return {};
// stub an instance
const stub = constructors.get(label);
if (stub === undefined) {
throw new Error(`Unknown stub type: ${label}`);
}
if ("stub" in stub) return stub.stub();
else return undefined;
}
function hydrateObject(
label: string,
stub: object,
val: any,
constructors: ConstructorMap,
) {
if (label === PLAIN_OBJECT_LABEL) {
const object = stub as Record<string, any>;
for (let i = 0; i < val.length; i += 2) {
object[val[i]] = val[i + 1];
}
return object;
}
const hydrator = constructors.get(label);
if (hydrator === undefined) {
throw new Error(`Unknown object type: ${label}`);
}
if (!("hydrate" in hydrator)) {
throw new Error(`Do not know how to hydrate stub type: ${label}`);
}
hydrator.hydrate(stub, val);
}
function createObject(label: string, val: any, constructors: ConstructorMap) {
const creator = constructors.get(label);
if (creator === undefined) {
throw new Error(`Unknown object type: ${label}`);
}
if (!("create" in creator)) {
throw new Error(`Do not know how to create object type: ${label}`);
}
return creator.create(val);
}
/**
* Converts a value to Oson data. Oson data only contains numbers, strings,
* arrays, and null values, and can therefore be JSON-encoded. This will
* preserve circular and repeated references as well as undefined, sparse
* arrays, bigint, and all classes instances defined by the constructor map.
*
* @param value The value to convert to Oson data
* @param constructors The constructor map to use for class instances
* @returns The Oson data containing the encoded value
*/
export function listify<C = any>(
value: unknown,
constructors: ConstructorMap<C> = GLOBAL_CONSTRUCTOR_MAP,
): Oson {
const num = toMagicNumber(value);
if (num !== null) return num;
const list: OsonValue[] = [];
const index = new Map<unknown, number>();
add(value);
return list;
function add(value: unknown): number {
const num = toMagicNumber(value);
if (num !== null) return num;
let position = index.get(value);
if (position !== undefined) return position;
position = list.length;
switch (typeof value) {
case "number":
case "string":
case "boolean":
list[position] = value;
index.set(value, position);
break;
case "bigint": {
list[position] = [BIG_INT_LABEL, value.toString(16)];
index.set(value, position);
break;
}
case "object":
if (value === null) {
list[position] = value;
index.set(value, position);
} else if (Array.isArray(value)) {
const arr: OsonArray = sparse(value.length);
list[position] = arr;
index.set(value, position);
for (const i in value) {
arr[i] = add(value[i]);
}
} else {
const [label, vals] = fromObject(value, constructors);
const len = vals.length;
const arr = Array(len + 1) as OsonObject;
arr[0] = label;
list[position] = arr;
index.set(value, position);
for (let i = 0; i < len; i++) {
arr[i + 1] = add(vals[i]);
}
}
}
return position;
}
}
/**
* Converts a Oson data back to a value. This will restore circular and repeated
* references as well as undefined, sparse arrays, bigint, and all classes
* instances defined by the constructor map.
*
* @param oson The Oson data to convert
* @param constructors The constructor map to use for class instances
* @returns The decoded value
*/
export function delistify<C = any>(
oson: Oson,
constructors: ConstructorMap<C> = GLOBAL_CONSTRUCTOR_MAP,
): any {
if (!Array.isArray(oson)) {
const val = fromMagicNumber(oson);
if (val !== null) return val;
else throw new Error(`Invalid Oson: ${oson}`);
}
if (oson.length === 0) throw new Error("Empty Oson data!");
const list = oson;
const index = Array(oson.length);
recover(0);
return index[0];
function recover(position: number) {
const val = fromMagicNumber(position);
if (val !== null) return val;
if (!(position in index)) {
const value = list[position];
switch (typeof value) {
case "object":
if (value !== null) {
if (isOsonBigInt(value)) {
const val = value[1];
const num = val.startsWith("-")
? -BigInt("0x" + val.substring(1))
: BigInt("0x" + val);
index[position] = num;
} else if (isOsonObject(value)) {
const [label, ...vals] = value;
const stub = stubObject(label, constructors);
if (stub === undefined) {
const v = vals.map(recover);
const o = createObject(label, v, constructors);
index[position] = o;
} else {
index[position] = stub;
const v = vals.map(recover);
hydrateObject(label, stub, v, constructors);
}
} else {
const len = value.length;
const array = Array(len);
index[position] = array;
for (let i = 0; i < len; i++) {
const val = value[i];
if (val !== ARRAY_HOLE_INDEX) {
array[i] = recover(val);
}
}
}
break;
}
// fallthrough for null
case "string":
case "boolean":
case "number":
index[position] = value;
break;
}
}
return index[position];
}
}