use crate::application::index::validate_mutable_output;
use leto::{ArrayViewMut, Layout, LetoError, Result};
pub fn coordinate_map_inplace<T, F, const N: usize>(
view: &mut ArrayViewMut<'_, T, N>,
coordinates: &[[usize; N]],
mut f: F,
) -> Result<()>
where
F: FnMut(usize, [usize; N], &mut T),
{
validate_mutable_output(view, "coordinate mutable map")?;
let shape = view.shape();
let layout = view.layout();
let data = view.data_mut();
for (ordinal, &index) in coordinates.iter().enumerate() {
if index
.iter()
.zip(shape.iter())
.any(|(&component, &axis)| component >= axis)
{
return Err(LetoError::OutOfBounds {
index: index.to_vec(),
shape: shape.to_vec(),
});
}
let offset = layout.offset_of(index)?;
f(ordinal, index, &mut data[offset]);
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CoordinateMapEntry<const N: usize> {
ordinal: usize,
index: [usize; N],
offset: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoordinateMapPlan<const N: usize> {
layout: Layout<N>,
entries: Vec<CoordinateMapEntry<N>>,
}
impl<const N: usize> CoordinateMapPlan<N> {
pub fn new<T>(view: &ArrayViewMut<'_, T, N>, coordinates: &[[usize; N]]) -> Result<Self> {
validate_mutable_output(view, "coordinate map plan")?;
let shape = view.shape();
let layout = view.layout();
let mut entries = Vec::with_capacity(coordinates.len());
for (ordinal, &index) in coordinates.iter().enumerate() {
if index
.iter()
.zip(shape.iter())
.any(|(&component, &axis)| component >= axis)
{
return Err(LetoError::OutOfBounds {
index: index.to_vec(),
shape: shape.to_vec(),
});
}
let offset = layout.offset_of(index)?;
entries.push(CoordinateMapEntry {
ordinal,
index,
offset,
});
}
Ok(Self { layout, entries })
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn layout(&self) -> &Layout<N> {
&self.layout
}
pub fn apply<T, F>(&self, view: &mut ArrayViewMut<'_, T, N>, mut f: F) -> Result<()>
where
F: FnMut(usize, [usize; N], &mut T),
{
validate_mutable_output(view, "coordinate map plan target")?;
if view.layout() != self.layout {
return Err(LetoError::StorageError {
reason: "coordinate map plan target layout differs from planned layout".to_string(),
});
}
let data = view.data_mut();
for entry in &self.entries {
f(entry.ordinal, entry.index, &mut data[entry.offset]);
}
Ok(())
}
}
pub fn coordinate_map_plan<T, const N: usize>(
view: &ArrayViewMut<'_, T, N>,
coordinates: &[[usize; N]],
) -> Result<CoordinateMapPlan<N>> {
CoordinateMapPlan::new(view, coordinates)
}
pub fn coordinate_map_plan_inplace<T, F, const N: usize>(
view: &mut ArrayViewMut<'_, T, N>,
plan: &CoordinateMapPlan<N>,
f: F,
) -> Result<()>
where
F: FnMut(usize, [usize; N], &mut T),
{
plan.apply(view, f)
}