Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make generic enum deserialization possible #2874

Open
vrurg opened this issue Dec 28, 2024 · 0 comments
Open

Make generic enum deserialization possible #2874

vrurg opened this issue Dec 28, 2024 · 0 comments

Comments

@vrurg
Copy link

vrurg commented Dec 28, 2024

At this moment, the only way to deserialize an enum is to know its structure at compile time. Unfortunately, this makes it impossible to deserialize an enum from a fully self-descriptive file format or when the file structure is backed by a schema. I would like to propose implementing a way of providing meta-information about enum variants at deserialization time.

How can this be useful? One example would be a generic converter between formats that can read schemas and do validated transformations without having access to the source code that created the originals.

Unfortunately, I'm not familiar enough with serde internals to suggest a detailed approach, but even a simple addition of something like a meta method to the VariantAccess trait would help a lot. The method can return something like VariantMeta:

enum VariantDescriptor<S> {
    Unit,
    Tuple {
        ty: Option<S>, // type name
        len: i32,
    },
    Newtype(Option<S>), // type name
    Struct, 
}
struct VariantMeta<S, T> {
    index: Option<i32>, // variant_index
    descriptor: VariantDescriptor<S>,
    properties: Option<HashMap<S, T>>, // if schema has more details; T is better be of a trait with methods like as_i32, as_str, etc.
}

For example, even without a schema, a YAML deserializer can peek at the lines, following a tagged variant, to find out whether it's a union, a tuple, or a struct. For a newtype, it's even easier since it's about peeking for the next value in the same string. The only issue here is with tuples, where finding out about their lengths would require scanning all lines up to the next declaration in the same level, which could be a bit time-consuming. But as soon as the functionality lands down in serde, I think a way to work around this would be found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant