Skip to content

inout: split a buffer in equal chunks #1170

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

Merged
merged 1 commit into from
Mar 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions inout/src/inout.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::InOutBuf;
use core::{marker::PhantomData, ptr};
use hybrid_array::{Array, ArraySize};
use core::{marker::PhantomData, ops::Mul, ptr};
use hybrid_array::{Array, ArraySize, typenum::Prod};

/// Custom pointer type which contains one immutable (input) and one mutable
/// (output) pointer, which are either equal or non-overlapping.
Expand Down Expand Up @@ -151,6 +151,28 @@ impl<'inp, 'out, T, N: ArraySize> InOut<'inp, 'out, Array<T, N>> {
}
}

impl<'inp, 'out, T, N, M> From<InOut<'inp, 'out, Array<T, Prod<N, M>>>>
for Array<InOut<'inp, 'out, Array<T, N>>, M>
where
N: ArraySize,
M: ArraySize,
N: Mul<M>,
Prod<N, M>: ArraySize,
{
fn from(buf: InOut<'inp, 'out, Array<T, Prod<N, M>>>) -> Self {
let in_ptr: *const Array<T, N> = buf.in_ptr.cast();
let out_ptr: *mut Array<T, N> = buf.out_ptr.cast();

Array::from_fn(|i| unsafe {
InOut {
in_ptr: in_ptr.add(i),
out_ptr: out_ptr.add(i),
_pd: PhantomData,
}
})
}
}

impl<N: ArraySize> InOut<'_, '_, Array<u8, N>> {
/// XOR `data` with values behind the input slice and write
/// result to the output slice.
Expand Down
34 changes: 34 additions & 0 deletions inout/tests/split-inout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use hybrid_array::{
Array,
sizes::{U2, U4, U8},
};
use inout::{InOut, InOutBuf};

#[test]
fn test_split() {
let mut buf = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
let inout: InOutBuf<'_, '_, u8> = buf.as_mut_slice().into();

let expected: Vec<&[u8]> = vec![
&[1, 2],
&[3, 4],
&[5, 6],
&[7, 8],
&[9, 10],
&[11, 12],
&[13, 14],
&[15, 16],
];
let mut expected = expected.into_iter();

let (blocks, _tail) = inout.into_chunks::<U8>();
for block in blocks.into_iter() {
type SubBlock = Array<u8, U2>;

let subblocks = Array::<InOut<'_, '_, SubBlock>, U4>::from(block);

for subblock in subblocks {
assert_eq!(Some(subblock.get_in().as_slice()), expected.next());
}
}
}