Is it feasible to support "prototypes" for "newtype enums"?

Newtype enums

An enum is considered a newtype if all of its variants is in the form of Variant( Type ), e.g.

enum Value {
    Bin( Vec<u8> ),
    Text( String ),
}

is a newtype enum.

Prototypes of newtype enums

By erasing the name and all its variants' names of an enum, we get its prototype. For instance, the prototype of Value is

enum __2 {
    _0( Vec<u8> ),
    _1( String ),
}

The prototype trait

pub trait Proto {
    type Type;
    fn from_proto( src: Self::Type ) -> Self;
    fn into_proto( self ) -> Self::Type;
}

Can rustc auto-implement this trait for any user-defined enum type?

impl Proto for Value {
    type Type = std::enum_proto::__2;

    fn from_proto( src:: Self::Type ) -> Self {
        match src {
            std::enum_proto::__2::_0(v) => Value::Bin(v),
            std::enum_proto::__2::_1(v) => Value::Text(v),
        }
    }

    fn into_proto( self ) -> Self::Type {
        match self {
            Value::Bin(v) => std::enum_proto::__2::_0(v),
            Value::Text(v) => std::enum_proto::__2::_1(v),
        }
    }
}

Purpose of enum prototype

It is helpful for simulating language features ad-hoc enums, anonymous enums, structural enums, ... you name it.

derive-more can do the From portion of this.

It can't do the Into portion, but in general nothing can (how would you infallibly turn Value::Bin(_) into a String?); TryInto would be the trait to target but derive-more doesn't do that yet.

No, I don't think Into is an issue( I have edited the main post, see ), but this is off-topic.

It is not possible for the "derive-more" crate or any other crate to setup the equivalence of a series of enum types __0, __1, .. (as needed) in std::enum_proto. The best we can get is a predefined range of varaints up to some fixed value( e.g. 16 ). Then comes an enum of 42 variants and the game is over.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.