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

Implement from_Xe_bytes, to_Xe_bytes, to_Xe and from_Xe for bitwidths… #17

Merged
merged 2 commits into from
May 15, 2023

Conversation

danlehmann
Copy link
Owner

… that are a multiple of 8

This needs some macro magic unfortunately as you can't specify const generic bounds like "multiple of 8".

The macros expand to this (for u24):

    pub const fn to_le_bytes(&self) -> [u8; 24 >> 3] {
        let v = self.value();

        [(v >> (0 << 3)) as u8, (v >> (1 << 3)) as u8, (v >> (2 << 3)) as u8, ]
    }

    pub const fn from_le_bytes(from: [u8; 24 >> 3]) -> Self {
        let value = { 0 | (from[0] as u32) << (0 << 3) | (from[1] as u32) << (1 << 3) | (from[2] as u32) << (2 << 3) };
        Self { value }
    }

    pub const fn to_be_bytes(&self) -> [u8; 24 >> 3] {
        let v = self.value();

        [(v >> (24 - 8 - (0 << 3))) as u8, (v >> (24 - 8 - (1 << 3))) as u8, (v >> (24 - 8 - (2 << 3))) as u8, ]
    }

    pub const fn from_be_bytes(from: [u8; 24 >> 3]) -> Self {
        let value = { 0 | (from[0] as u32) << (24 - 8 - (0 << 3)) | (from[1] as u32) << (24 - 8 - (1 << 3)) | (from[2] as u32) << (24 - 8 - (2 << 3)) };
        Self { value }
    }

… that are a multiple of 8

This needs some macro magic unfortunately as you can't specify const generic bounds like "multiple of 8".

The macros expand to this (for u24):

```
    pub const fn to_le_bytes(&self) -> [u8; 24 >> 3] {
        let v = self.value();

        [(v >> (0 << 3)) as u8, (v >> (1 << 3)) as u8, (v >> (2 << 3)) as u8, ]
    }

    pub const fn from_le_bytes(from: [u8; 24 >> 3]) -> Self {
        let value = { 0 | (from[0] as u32) << (0 << 3) | (from[1] as u32) << (1 << 3) | (from[2] as u32) << (2 << 3) };
        Self { value }
    }

    pub const fn to_be_bytes(&self) -> [u8; 24 >> 3] {
        let v = self.value();

        [(v >> (24 - 8 - (0 << 3))) as u8, (v >> (24 - 8 - (1 << 3))) as u8, (v >> (24 - 8 - (2 << 3))) as u8, ]
    }

    pub const fn from_be_bytes(from: [u8; 24 >> 3]) -> Self {
        let value = { 0 | (from[0] as u32) << (24 - 8 - (0 << 3)) | (from[1] as u32) << (24 - 8 - (1 << 3)) | (from[2] as u32) << (24 - 8 - (2 << 3)) };
        Self { value }
    }
```
@danlehmann danlehmann merged commit 5fb6af0 into main May 15, 2023
@danlehmann danlehmann deleted the from_and_to_bytes branch May 15, 2023 18:10
@danlehmann danlehmann mentioned this pull request May 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants