6 #include "metamethods.h"
13 PUREFUNC bool is_none(const void *obj, const TypeInfo_t *non_optional_type) {
14 if (non_optional_type->metamethods.is_none) return non_optional_type->metamethods.is_none(obj, non_optional_type);
16 const bool *has_value = (const bool *)(obj + non_optional_type->size);
20 PUREFUNC public uint64_t Optional$hash(const void *obj, const TypeInfo_t *type) {
21 return is_none(obj, type->OptionalInfo.type) ? 0 : generic_hash(obj, type->OptionalInfo.type);
24 PUREFUNC public int32_t Optional$compare(const void *x, const void *y, const TypeInfo_t *type) {
26 bool x_is_null = is_none(x, type->OptionalInfo.type);
27 bool y_is_null = is_none(y, type->OptionalInfo.type);
28 if (x_is_null && y_is_null) return 0;
29 else if (x_is_null != y_is_null) return (int32_t)y_is_null - (int32_t)x_is_null;
30 else return generic_compare(x, y, type->OptionalInfo.type);
33 PUREFUNC public bool Optional$equal(const void *x, const void *y, const TypeInfo_t *type) {
34 if (x == y) return true;
36 bool x_is_null = is_none(x, type->OptionalInfo.type);
37 bool y_is_null = is_none(y, type->OptionalInfo.type);
38 if (x_is_null && y_is_null) return true;
39 else if (x_is_null != y_is_null) return false;
40 else return generic_equal(x, y, type->OptionalInfo.type);
44 Text_t Optional$as_text(const void *obj, bool colorize, const TypeInfo_t *type) {
45 if (!obj) return Text$concat(generic_as_text(obj, colorize, type->OptionalInfo.type), Text("?"));
47 if (is_none(obj, type->OptionalInfo.type)) return colorize ? Text("\x1b[31mnone\x1b[m") : Text("none");
48 return generic_as_text(obj, colorize, type->OptionalInfo.type);
52 void Optional$serialize(const void *obj, FILE *out, Table_t *pointers, const TypeInfo_t *type) {
53 bool has_value = !is_none(obj, type->OptionalInfo.type);
54 assert(fputc((int)has_value, out) != EOF);
55 if (has_value) _serialize(obj, out, pointers, type->OptionalInfo.type);
59 void Optional$deserialize(FILE *in, void *outval, List_t *pointers, const TypeInfo_t *type) {
60 bool has_value = (bool)fgetc(in);
61 const TypeInfo_t *nonnull = type->OptionalInfo.type;
63 memset(outval, 0, (size_t)type->size);
64 _deserialize(in, outval, pointers, nonnull);
66 if (nonnull->tag == TextInfo) *(Text_t *)outval = NONE_TEXT;
67 else if (nonnull->tag == ListInfo) *(List_t *)outval = NONE_LIST;
68 else if (nonnull->tag == TableInfo) *(Table_t *)outval = NONE_TABLE;
69 else if (nonnull == &Num$info) *(double *)outval = (double)NAN;
70 else if (nonnull == &Num32$info) *(float *)outval = (float)NAN;
71 else if (nonnull->tag == StructInfo || (nonnull->tag == OpaqueInfo && type->size > nonnull->size))
72 memset(outval + type->size, -1, (size_t)(type->size - nonnull->size));
73 else memset(outval, 0, (size_t)type->size);