Skip to content

Commit 9856d9f

Browse files
committed
finish implementing Box<T>
1 parent 0886062 commit 9856d9f

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

assembly/index.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ export namespace JSON {
156156
return deserializeInteger<T>(dataPtr, dataPtr + dataSize);
157157
} else if (isFloat<T>()) {
158158
return deserializeFloat<T>(dataPtr, dataPtr + dataSize);
159-
} else if (isNullable<T>() && data.length == 4 && data == "null") {
159+
} else if (isNullable<T>() && dataSize == 8 && load<u64>(dataPtr) == 30399761348886638) {
160160
// @ts-ignore
161161
return null;
162162
} else if (isString<T>()) {
@@ -182,7 +182,7 @@ export namespace JSON {
182182
return deserializeDate(dataPtr, dataPtr + dataSize);
183183
} else if (type instanceof JSON.Box) {
184184
// @ts-ignore
185-
return new JSON.Box(JSON.parse<indexof<T>>(data));
185+
return new JSON.Box(parseBox(data, changetype<nonnull<T>>(0).value));
186186
} else {
187187
throw new Error(`Could not deserialize data ${data} to type ${nameof<T>()}. Make sure to add the correct decorators to classes.`);
188188
}
@@ -339,7 +339,9 @@ export namespace JSON {
339339
* Box for primitive types
340340
*/
341341
export class Box<T> {
342-
constructor(public value: T) {}
342+
constructor(public value: T) {
343+
if (!isInteger<T>() && !isFloat<T>()) ERROR("JSON.Box should only hold primitive types!");
344+
}
343345
/**
344346
* Creates a reference to a primitive type
345347
* This means that it can create a nullable primitive
@@ -353,6 +355,12 @@ export namespace JSON {
353355
@inline static from<T>(value: T): Box<T> {
354356
return new Box(value);
355357
}
358+
toString(): string {
359+
if (isNullable<this>() && changetype<usize>(this) == null) return "null";
360+
// @ts-ignore: type
361+
if (isDefined(this.value.toString)) return this.value.toString();
362+
return "null";
363+
}
356364
}
357365

358366
export function __serialize<T>(src: T): void {
@@ -423,9 +431,18 @@ export namespace JSON {
423431
return deserializeDate(srcStart, srcEnd);
424432
} else if (type instanceof JSON.Box) {
425433
// @ts-ignore: type
426-
return new JSON.Box(__deserialize<indexof<T>>(srcStart, srcEnd));
434+
return new JSON.Box(deserializeBox(srcStart, srcEnd, dst, changetype<nonnull<T>>(0).value));
427435
}
428436
}
429437
throw new Error(`Could not deserialize data '${ptrToStr(srcStart, srcEnd).slice(0, 100)}' to type. Make sure to add the correct decorators to classes.`);
430438
}
431439
}
440+
441+
// @ts-ignore: decorator
442+
@inline function parseBox<T>(data: string, ty: T): T {
443+
return JSON.parse<T>(data);
444+
}
445+
446+
function deserializeBox<T>(srcStart: usize, srcEnd: usize, dst: usize, ty: T): T {
447+
return JSON.__deserialize<T>(srcStart, srcEnd, dst);
448+
}

0 commit comments

Comments
 (0)