Created
April 17, 2026 07:11
-
-
Save chanmix51/5e47344e34b7055102582b15243f2b45 to your computer and use it in GitHub Desktop.
Define a trait that holds real type internal data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use anyhow; // 1.0.102 | |
| type Result<T> = anyhow::Result<T>; | |
| pub trait ByteHolder { | |
| fn get_bytes(&self) -> &[u8]; | |
| fn from_bytes(bytes: Vec<u8>) -> Result<Self> where Self: Sized; | |
| } | |
| #[derive(Debug, PartialEq, Eq)] | |
| pub struct DumbByteHolder { | |
| bytes: Vec<u8> | |
| } | |
| impl ByteHolder for DumbByteHolder { | |
| fn get_bytes(&self) -> &[u8] { | |
| self.bytes.as_slice() | |
| } | |
| fn from_bytes(bytes: Vec<u8>) -> Result<Self> where Self: Sized { | |
| Ok(Self { bytes }) | |
| } | |
| } | |
| #[derive(Debug, PartialEq, Eq)] | |
| pub struct TceInt<T>(T) | |
| where T: ByteHolder + ?Sized; | |
| impl<T: ByteHolder> From<u16> for TceInt<T> { | |
| fn from(n: u16) -> Self { | |
| let byte_holder = T::from_bytes(n.to_be_bytes().to_vec()).unwrap(); | |
| Self(byte_holder) | |
| } | |
| } | |
| fn main() { | |
| let tce_int = TceInt(DumbByteHolder { bytes: vec![0x00, 0xff]}); | |
| assert_eq!(TceInt::from(255_u16), tce_int); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment