Skip to main content

repr_conv

Attribute Macro repr_conv 

Source
#[repr_conv]
Expand description

An attribute macro that mimics the syntax and behavior of repr(u*)/repr(i*) but additionally implements std::convert::From and std::convert::TryFrom traits to provide practical and sensible conversions between annontated enum variants and respective integer values.

repr_conv accepts a single parameter which is a primitive integer type.

#[repr_conv(u16)]
#[derive(Debug, PartialEq, Eq)]
enum SupportedPorts {
    FTP = 21,
    SSH, // = 22
    HTTP = 80,
    HTTPS = 443,
}

// we can get a u16 for the FTP port easily...
assert_eq!(u16::from(SupportedPorts::FTP), 21);
//... and for the SSH port too
assert_eq!(u16::from(SupportedPorts::SSH), 22);
// HTTP port is supported and so conversion succeeds
assert_eq!(SupportedPorts::try_from(80).unwrap(), SupportedPorts::HTTP);
// Gopher is not supported; who needs it in 2025?!
assert!(SupportedPorts::try_from(70).is_err());