I am following a guide for implementing a serializer with serde. It gives a basic implementation of a JSON serializer using Serde. Say that I only want to serialize the unsigned integers u8, u16 and u32. Is it possible to somehow specify this constraint and throw errors whenever the user tries to serialize any other type like string, f32 etc. ?
I could probably write
fn serialize_string(self, v: string) -> Result<()> {
return Err(Error::Message("Undefined".to_owned()));
}
fn serialize_f32(self, v: f32) -> Result<()> {
return Err(Error::Message("Undefined".to_owned()));
}
/* and so forth */
But this feels too verbose.
And is it possible to define a protocol for serializing custom types? For example I might have a struct Point containing two coordinates x and y. I want to serialize Point in a compressed format as explained here: https://bitcoin.stackexchange.com/a/84588, I.e. serialize the first x coordinate as any other unsigned integer but add a small prefix to indicate if the y coordinate is even or odd. One can then derive y from x by using the prefix (conditional).