Added more checks for optional serialization support.
This commit is contained in:
parent
8abb3a2c42
commit
ac3a070944
|
|
@ -100,6 +100,12 @@ 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) {
|
||||||
|
static if (!__traits(compiles, {T t; t = T.init;})) {
|
||||||
|
return new SerdeException(
|
||||||
|
"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 {
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
this.isNull = true;
|
this.isNull = true;
|
||||||
this.value = T.init;
|
this.value = T.init;
|
||||||
|
|
@ -109,6 +115,7 @@ struct Optional(T) {
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serializes an optional value to allow for the automatic serialization
|
* Serializes an optional value to allow for the automatic serialization
|
||||||
|
|
@ -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.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue