While making our Deserialize, we found the following to work quite well:
impl<'de, T: Deserialize<'de>> Deserialize<'de> for MayBe<T> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let mut depth: usize = 0;
let content = match <serde::__private::de::Content as serde::Deserialize>::deserialize(d) {
Ok(val) => val,
Err(e) => {
return Err(e);
}
};
match Deserialize::deserialize(MayBeDer(&mut depth, serde::__private::de::ContentRefDeserializer::<D::Error>::new(&content))) {
Ok(t) => Ok(MayBe::Is(t)),
Err(_) if depth == 0 => Ok(MayBe::IsNot),
Err(e) => Err(e),
}
}
}
However, this relies on internals of how untagged enums work in serde. Unfortunately we don't seem to be able to make this work with #[serde(deserialize_with)] because that requires a T and not a MayBe<T>. Any ideas for how to make this work without serde internals, and ideally without writing another two Deserializer impls and another Visitor?