Added more checks for optional serialization support.
Build and Test Module / build-and-test (push) Successful in 6s Details
Build and Test Module / build-and-test-with-asdf-library (push) Successful in 11s Details

This commit is contained in:
Andrew Lalis 2026-06-15 15:20:21 -04:00
parent 8abb3a2c42
commit ac3a070944
1 changed files with 29 additions and 6 deletions

View File

@ -100,14 +100,21 @@ struct Optional(T) {
* Returns: An exception if one is thrown. * Returns: An exception if one is thrown.
*/ */
SerdeException deserializeFromAsdf(Asdf data) { SerdeException deserializeFromAsdf(Asdf data) {
if (data == null) { static if (!__traits(compiles, {T t; t = T.init;})) {
this.isNull = true; return new SerdeException(
this.value = T.init; "Cannot deserialize Optional that contains immutable or otherwise unassignable value. " ~
"Ensure that the following code compiles: T t; t = T.init; for the given type T."
);
} else { } else {
this.isNull = false; if (data == null) {
this.value = deserialize!T(data); this.isNull = true;
this.value = T.init;
} else {
this.isNull = false;
this.value = deserialize!T(data);
}
return null;
} }
return null;
} }
/** /**
@ -183,5 +190,21 @@ unittest {
assert(sa.b && sa.b.value == "hello world!"); assert(sa.b && sa.b.value == "hello world!");
assert(sa.c && sa.c.value == 3.14f); assert(sa.c && sa.c.value == 3.14f);
assert(sa.d && sa.d.value == Sd(42, 67)); assert(sa.d && sa.d.value == Sd(42, 67));
// Check that optionals containing immutable data aren't supported for serialization & deserialization:
struct Invalid {
immutable int x;
}
Optional!Invalid opt = Optional!(Invalid).of(Invalid(42));
static assert(!__traits(compiles, serializeToJson(opt)));
try {
deserialize!(Optional!(Invalid))(`{"x": 123}`);
assert(
false,
"Failed to ensure that an exception is thrown when attempting to deserialize an incompatible Optional."
);
} catch (SerdeException exc) {
// pass.
}
} }
} }