rozbb / saber-rs

A pure-Rust implementation of the Saber key encapsulation mechanism (KEM)
Other
4 stars 1 forks source link

Type alias for all `&[u8; SIZE_SOMETHING]` #7

Closed pinkforest closed 3 weeks ago

pinkforest commented 3 weeks ago

Reduces repeating it and ensures it is consistent all over the place potentially reducing errors / confusion given it's tagged.

Same as ed25519_dalek::SecretKey

Also helps documenting it.

rozbb commented 3 weeks ago

Can you give an example? All of them use a const where possible rn

pinkforest commented 3 weeks ago

https://github.com/rozbb/saber-rs/blob/main/src/impls.rs#L20-26

I know type alias has some footguns sans newtype as now but it would still help to alias the sized slice with it that it's fine for the compiler to treat them same within inside newtype.

pub type BYTES_32 = [u8; 32];

/// A shared secret of a KEM execution. This is just a `[u8; 32]` that zeroes itself from memory
/// when it goes out of scope.
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct SharedSecret(BYTES_32);

impl SharedSecret {
    /// Returns the shared secret as a slice
    #[inline]
    pub fn as_bytes(&self) -> &BYTES_32 {
        &self.0
    }
}
rozbb commented 3 weeks ago

Ah ok, works for me. Is 32 the only constant?

pinkforest commented 3 weeks ago

All the diff sizes -

Also an idea could be to denote it's use via name inside newtype avoiding the footgun but yet documenting it.

e.g.

/// All Shared secrets are 32 bytes fixed size
pub type SIZED_SHARED_SECRET = [u8; 32];

/// Newtype to protect SharedSecret type
pub struct SharedSecret(SIZED_SHARED_SECRET)
pinkforest commented 3 weeks ago

Sigh actually that is a bad idea mixing the names as the compiler still sees them as same and passing a struct (newtype) isnt' really feasible :] so better just to say BYTES_32 so it doesn't confuse that it's somehow separate type.

pinkforest commented 3 weeks ago

Yeah I'll just close this - might not be feasible but up to you I always kinda have difficulty reading [x; Y] vs XXX_YYY just a nit