#[cfg(any(feature = "npz", feature = "pth"))]
pub(crate) fn byteswap_inplace(data: &mut [u8], element_size: usize) {
for chunk in data.chunks_exact_mut(element_size) {
chunk.reverse();
}
}
#[must_use]
pub(crate) fn checked_num_elements(shape: &[usize]) -> Option<usize> {
shape.iter().try_fold(1usize, |acc, &d| acc.checked_mul(d))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn checked_num_elements_basic() {
assert_eq!(checked_num_elements(&[]), Some(1));
assert_eq!(checked_num_elements(&[16384, 2304]), Some(16384 * 2304));
assert_eq!(checked_num_elements(&[0, 5]), Some(0));
}
#[test]
fn checked_num_elements_overflow_is_none() {
assert_eq!(checked_num_elements(&[usize::MAX, 2]), None);
}
#[cfg(any(feature = "npz", feature = "pth"))]
#[test]
fn byteswap_2byte() {
let mut data = vec![0x01, 0x02, 0x03, 0x04];
byteswap_inplace(&mut data, 2);
assert_eq!(data, vec![0x02, 0x01, 0x04, 0x03]);
}
#[cfg(any(feature = "npz", feature = "pth"))]
#[test]
fn byteswap_4byte() {
let mut data = vec![0x01, 0x02, 0x03, 0x04];
byteswap_inplace(&mut data, 4);
assert_eq!(data, vec![0x04, 0x03, 0x02, 0x01]);
}
#[cfg(any(feature = "npz", feature = "pth"))]
#[test]
fn byteswap_8byte() {
let mut data = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
byteswap_inplace(&mut data, 8);
assert_eq!(data, vec![0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01]);
}
#[cfg(any(feature = "npz", feature = "pth"))]
#[test]
fn byteswap_1byte_is_noop() {
let mut data = vec![0xAA, 0xBB, 0xCC];
byteswap_inplace(&mut data, 1);
assert_eq!(data, vec![0xAA, 0xBB, 0xCC]);
}
#[cfg(any(feature = "npz", feature = "pth"))]
#[test]
fn byteswap_empty() {
let mut data: Vec<u8> = vec![];
byteswap_inplace(&mut data, 4);
assert!(data.is_empty());
}
}