hybrid-array: add Flatten and Unflatten traits#170
Conversation
These were extracted from the `module-lattice` crate (which in turn was extracted from `ml-dsa`). They were contributed by @bifurcation and seem generally useful. I have extracted them largely verbatim except cleaning up a few things which were triggering lint failures. Having them as traits instead of inherent methods is nice because you can bound on them, where the bounds they actually require would be somewhat annoying to have downstream code repeat.
newpavlov
left a comment
There was a problem hiding this comment.
This seems fine to me, but the traits looks a bit weird on the first glance, especially considering that we are unlikely to have more than one impl for them.
Having them as traits instead of inherent methods is nice because you can bound on them, where the bounds they actually require would be somewhat annoying to have downstream code repeat.
So you effectively want trait aliases, right? Maybe we could introduce inherent methods and use the traits just as pseudo-aliases?
Yeah, something like That said, having something like that may be necessary, as I tried ditching the traits entirely and moving to inherent methods and got Didn't look too long, but this is what I was trying: impl<T, N, M> Array<T, N>
where
N: ArraySize + Div<M> + Rem<M, Output = U0>,
M: ArraySize,
Quot<N, M>: ArraySize,
{
pub fn unflatten(self) -> Array<Array<T, Quot<N, M>>, M> {
let part_size = Quot::<N, M>::USIZE;
let whole = ManuallyDrop::new(self);
// SAFETY: this is doing the same thing as what is done in `Array::split`.
// Basically, this is doing transmute between [T; K*N] and [[T; K], M], which is guaranteed
// to be safe by the Rust memory layout of these types.
Array::from_fn(|i| unsafe {
let offset = i.checked_mul(part_size).expect("overflow");
ptr::read(whole.as_ptr().add(offset).cast())
})
}
}I think I'll merge this as-is but not release right away if you want to take a crack at it @newpavlov. |
They're now in `hybrid-array` as of v0.4.7: RustCrypto/hybrid-array#170
These were extracted from the
module-latticecrate (which in turn was extracted fromml-dsa).They were contributed by @bifurcation and seem generally useful. I have extracted them largely verbatim except cleaning up a few things which were triggering lint failures.
Having them as traits instead of inherent methods is nice because you can bound on them, where the bounds they actually require would be somewhat annoying to have downstream code repeat.