How to parse a type with invariants with serde

โš“ Rust    ๐Ÿ“… 2025-09-23    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 8      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

Following the concept of Parse, donโ€™t validate I am wondering how to actually do this in practice with serde.

For example lets say we have the following struct:

pub struct OrderedPair<T: Ord>(T, T);

impl<T: Ord> OrderedPair<T> {
    pub fn new(left: T, right: T) -> Option<Self> {
        if left > right {
            None
        } else {
            Some(Self(left, right))
        }
    }
}

So far so good we have a type with some invariant that gets checked when instantiating it. But now I want to make this type deserializable. If I know just derive(Deserialize) then the check of new won't be used and I could deserialize an invalid state, so basically the invariant is not guaranteed anymore.

Of course I can implement Deserialize myself but that seems a bit tedious for such a simple and very regular task as validating some invariant. Is there any better option than implementing Deserialize myself? Just note that this is a simple example in practice the structs might be bigger and the invariants more complicated.

3 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed