use crate::codestream::MainHeader;
use crate::codestream::markers::{PocVolume, Progression, Rect, Siz};
use crate::{Error, Result};
use super::geometry::ResolutionGeom;
use super::{Meter, WorkRefusal};
pub(crate) struct PacketWalk<'a> {
pub(crate) siz: &'a Siz,
pub(crate) tile: Rect,
pub(crate) geoms: &'a [Vec<ResolutionGeom>],
}
impl PacketWalk<'_> {
fn sampling(&self, comp: usize) -> (u64, u64) {
let c = &self.siz.components[comp];
(u64::from(c.x_sampling), u64::from(c.y_sampling))
}
fn level(&self, comp: usize, res: usize) -> u32 {
(self.geoms[comp].len() - 1 - res) as u32
}
fn precinct_at(&self, comp: usize, res: usize, x: u64, y: u64) -> Option<usize> {
let geom = &self.geoms[comp][res];
if geom.precinct_count() == 0 {
return None;
}
let level = self.level(comp, res);
let (dx, dy) = self.sampling(comp);
let (sx, sy) = (dx << level, dy << level);
let (tx0, ty0) = (u64::from(self.tile.x0), u64::from(self.tile.y0));
let (tx1, ty1) = (u64::from(self.tile.x1), u64::from(self.tile.y1));
let (trx0, trx1) = (tx0.div_ceil(sx), tx1.div_ceil(sx));
let (try0, try1) = (ty0.div_ceil(sy), ty1.div_ceil(sy));
if trx0 == trx1 || try0 == try1 {
return None;
}
let (rpx, rpy) = (geom.ppx + level, geom.ppy + level);
let (px, py) = (dx << rpx, dy << rpy);
let corner = |v: u64, t0: u64, tr0: u64, span: u64, exp: u32| {
v.is_multiple_of(span) || (v == t0 && !(tr0 << level).is_multiple_of(1u64 << exp))
};
if !corner(y, ty0, try0, py, rpy) || !corner(x, tx0, trx0, px, rpx) {
return None;
}
let i = (x.div_ceil(sx) >> geom.ppx) - (trx0 >> geom.ppx);
let j = (y.div_ceil(sy) >> geom.ppy) - (try0 >> geom.ppy);
debug_assert!(
i < geom.precincts_wide as u64 && j < geom.precincts_high as u64,
"precinct index ({i}, {j}) out of the {}x{} grid",
geom.precincts_wide,
geom.precincts_high,
);
Some(j as usize * geom.precincts_wide + i as usize)
}
fn spans(&self, comp: usize) -> (Option<u64>, Option<u64>) {
let (dx, dy) = self.sampling(comp);
let mut spans = (None, None);
for (res, geom) in self.geoms[comp].iter().enumerate() {
let level = self.level(comp, res);
spans.0 = min_some(spans.0, shl32(dx, geom.ppx + level));
spans.1 = min_some(spans.1, shl32(dy, geom.ppy + level));
}
spans
}
}
fn min_some(a: Option<u64>, b: Option<u64>) -> Option<u64> {
match (a, b) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
fn both(spans: (Option<u64>, Option<u64>)) -> Option<(u64, u64)> {
Some((spans.0?, spans.1?))
}
fn shl32(value: u64, shift: u32) -> Option<u64> {
let scaled = value.checked_shl(shift)?;
(scaled <= u64::from(u32::MAX)).then_some(scaled)
}
pub(crate) struct Volume {
progression: Progression,
layers: u32,
resolutions: std::ops::Range<usize>,
components: std::ops::Range<usize>,
}
#[derive(Default)]
struct Plan {
held: Vec<Vec<usize>>,
spans: Vec<(Option<u64>, Option<u64>)>,
step: Option<(u64, u64)>,
}
impl Plan {
fn new(walk: &PacketWalk<'_>, max_res: usize, volumes: &[Volume]) -> Self {
let mut held = vec![Vec::new(); max_res];
for (comp, resolutions) in walk.geoms.iter().enumerate() {
for (res, geom) in resolutions.iter().enumerate() {
if geom.precinct_count() > 0 {
held[res].push(comp);
}
}
}
let sweeps = volumes.iter().any(|v| {
matches!(
v.progression,
Progression::Rpcl | Progression::Pcrl | Progression::Cprl
)
});
let spans: Vec<_> = if sweeps {
(0..walk.geoms.len()).map(|c| walk.spans(c)).collect()
} else {
Vec::new()
};
let all = spans.iter().fold((None, None), |acc, s| {
(min_some(acc.0, s.0), min_some(acc.1, s.1))
});
Plan {
held,
spans,
step: both(all),
}
}
fn held_range(&self, res: usize, range: &std::ops::Range<usize>) -> (usize, usize) {
let comps = &self.held[res];
let start = comps.partition_point(|&c| c < range.start);
let end = comps.partition_point(|&c| c < range.end);
(start, end.max(start))
}
}
type PairList = Vec<(usize, usize)>;
type ListRun = (usize, std::ops::Range<usize>);
fn pair_lists(
plan: &Plan,
components: usize,
max_res: usize,
volumes: &[Volume],
) -> (Vec<PairList>, Vec<ListRun>) {
let swept = |v: &Volume| matches!(v.progression, Progression::Pcrl | Progression::Cprl);
let whole = |v: &Volume| v.resolutions.start == 0 && v.resolutions.end >= max_res;
let build = |components: &std::ops::Range<usize>, resolutions: &std::ops::Range<usize>| {
let mut list: Vec<(usize, usize)> = resolutions
.clone()
.flat_map(|res| {
let (start, end) = plan.held_range(res, components);
plan.held[res][start..end].iter().map(move |&c| (c, res))
})
.collect();
list.sort_unstable();
list
};
let mut lists = Vec::new();
if volumes.iter().any(|v| swept(v) && whole(v)) {
lists.push(build(&(0..components), &(0..max_res)));
}
let mut owners: Vec<(usize, usize)> = Vec::new();
let pairs = volumes
.iter()
.enumerate()
.map(|(index, v)| {
if !swept(v) {
return (0, 0..0);
}
if whole(v) {
let list = &lists[0];
let start = list.partition_point(|&(c, _)| c < v.components.start);
let end = list.partition_point(|&(c, _)| c < v.components.end);
return (0, start..end.max(start));
}
let same = owners.iter().find(|&&(o, _)| {
volumes[o].resolutions == v.resolutions && volumes[o].components == v.components
});
let list = match same {
Some(&(_, list)) => list,
None => {
lists.push(build(&v.components, &v.resolutions));
owners.push((index, lists.len() - 1));
lists.len() - 1
}
};
(list, 0..lists[list].len())
})
.collect();
(lists, pairs)
}
pub(crate) fn check_poc_coverage(
header: &MainHeader,
walk: &PacketWalk<'_>,
tile: u32,
) -> Result<()> {
let layers = header.cod.layers;
poc_gaps(header, walk, |comp, res, reached| {
Err(Error::codestream(format!(
"the `POC` volumes of tile {tile} leave out its packets of component \
{comp}, resolution {res}, from layer {reached} of {layers}"
)))
})
}
pub(crate) fn poc_gaps(
header: &MainHeader,
walk: &PacketWalk<'_>,
mut gap: impl FnMut(usize, usize, u16) -> Result<()>,
) -> Result<()> {
if header.poc.is_empty() {
return Ok(());
}
let layers = header.cod.layers;
for (comp, resolutions) in walk.geoms.iter().enumerate() {
let covers = |v: &&PocVolume| (v.comp_start..v.comp_end).contains(&(comp as u16));
let mut full = 0u64;
for v in header.poc.iter().filter(covers) {
if v.layer_end >= layers {
let (start, end) = (u32::from(v.res_start).min(64), u32::from(v.res_end).min(64));
full |= mask_below(end) & !mask_below(start);
}
}
for (res, geom) in resolutions.iter().enumerate() {
if (full >> res) & 1 == 0 && geom.precinct_count() > 0 {
let reached = header
.poc
.iter()
.filter(covers)
.filter(|v| (usize::from(v.res_start)..usize::from(v.res_end)).contains(&res))
.map(|v| v.layer_end)
.max()
.unwrap_or(0);
gap(comp, res, reached)?;
}
}
}
Ok(())
}
fn mask_below(n: u32) -> u64 {
1u64.checked_shl(n).map_or(u64::MAX, |bit| bit - 1)
}
pub(crate) fn for_each_packet<F>(
header: &MainHeader,
walk: &PacketWalk<'_>,
meter: &Meter,
poc_bitmap: u64,
poc_counts: bool,
mut f: F,
) -> Result<()>
where
F: FnMut(u32, usize, usize, usize) -> Result<()>,
{
let order = Order::new(header, walk);
if order.volumes.len() == 1 {
return order.walk_runs(walk, meter, f);
}
let mut emitted = Emitted::new(
&order.volumes,
walk,
order.max_res,
meter,
poc_bitmap,
poc_counts,
)?;
let skip_visits = emitted.skip_visits();
order.walk_runs(walk, meter, |layer, res, comp, precinct| {
if emitted.insert(walk, layer, res, comp, precinct)? {
f(layer, res, comp, precinct)
} else if skip_visits > 0 {
meter.spend(skip_visits, WorkRefusal::PacketWalk)
} else {
Ok(())
}
})
}
pub(crate) const COUNTS_SKIP_VISITS: usize = 12;
pub(super) struct Emitted {
starts: Vec<u64>,
resolutions: usize,
marks: Marks,
}
enum Marks {
Dense(Vec<u64>),
Counts(Vec<u32>),
}
impl Emitted {
pub(super) fn new(
volumes: &[Volume],
walk: &PacketWalk<'_>,
resolutions: usize,
meter: &Meter,
dense_bits: u64,
poc_counts: bool,
) -> Result<Self> {
let (mut starts, reached) = Self::layout(volumes, walk, resolutions);
let words = usize::try_from(reached.div_ceil(64))
.ok()
.filter(|_| reached <= dense_bits);
let marks = match words {
_ if layer_orders(volumes) && reached > meter.left() => {
return Err(meter.refuse(WorkRefusal::PocReach { reached }));
}
Some(words) => Marks::Dense(vec![0; words]),
None if !poc_counts => {
return Err(Error::limit_fixed(
crate::LimitKind::PocVolumes,
format!(
"tile packet walk exceeds its work bound: its `POC` volumes hold \
{reached} packets, past the packet bitmap"
),
));
}
None => {
let mut precincts = 0u64;
for (index, start) in starts.iter_mut().enumerate() {
let (comp, res) = (index / resolutions, index % resolutions);
*start = precincts;
if let Some(geom) = walk.geoms[comp].get(res) {
precincts += geom.precinct_count() as u64;
}
}
let precincts = usize::try_from(precincts).map_err(|_| {
Error::inconsistent(format!("{precincts} precincts in one tile"))
})?;
Marks::Counts(vec![0; precincts])
}
};
Ok(Emitted {
starts,
resolutions,
marks,
})
}
fn layout(volumes: &[Volume], walk: &PacketWalk<'_>, resolutions: usize) -> (Vec<u64>, u64) {
let mut starts = vec![0u64; walk.geoms.len() * resolutions];
for volume in volumes {
for comp in volume.components.clone() {
let held = walk.geoms[comp].len();
for res in volume.resolutions.clone().filter(|&r| r < held) {
let layers = &mut starts[comp * resolutions + res];
*layers = (*layers).max(u64::from(volume.layers));
}
}
}
let mut reached = 0u64;
for (index, start) in starts.iter_mut().enumerate() {
let (comp, res) = (index / resolutions, index % resolutions);
let layers = std::mem::replace(start, reached);
if layers > 0 {
reached += layers * walk.geoms[comp][res].precinct_count() as u64;
}
}
(starts, reached)
}
fn skip_visits(&self) -> usize {
match self.marks {
Marks::Dense(_) => 0,
Marks::Counts(_) => COUNTS_SKIP_VISITS,
}
}
#[inline(never)]
pub(super) fn insert(
&mut self,
walk: &PacketWalk<'_>,
layer: u32,
res: usize,
comp: usize,
precinct: usize,
) -> Result<bool> {
let start = self.starts[comp * self.resolutions + res];
let precincts = walk.geoms[comp][res].precinct_count() as u64;
debug_assert!(
(precinct as u64) < precincts,
"precinct {precinct} of {precincts}"
);
match &mut self.marks {
Marks::Dense(words) => {
let bit = start + u64::from(layer) * precincts + precinct as u64;
let word = usize::try_from(bit / 64)
.ok()
.and_then(|w| words.get_mut(w))
.ok_or_else(|| {
Error::inconsistent(format!("packet {bit} past the `POC` bitmap"))
})?;
let mask = 1u64 << (bit % 64);
let new = *word & mask == 0;
*word |= mask;
Ok(new)
}
Marks::Counts(counts) => {
let count = usize::try_from(start + precinct as u64)
.ok()
.and_then(|at| counts.get_mut(at))
.ok_or_else(|| {
Error::inconsistent(format!("precinct {precinct} past the `POC` counts"))
})?;
if layer < *count {
Ok(false)
} else if layer == *count {
*count += 1;
Ok(true)
} else {
Err(Error::inconsistent(format!(
"layer {layer} of a precinct emitted before layer {count}"
)))
}
}
}
}
}
pub(crate) fn reached(volumes: &[Volume], walk: &PacketWalk<'_>, resolutions: usize) -> u64 {
Emitted::layout(volumes, walk, resolutions).1
}
pub(crate) fn layer_orders(volumes: &[Volume]) -> bool {
volumes
.iter()
.all(|v| matches!(v.progression, Progression::Lrcp | Progression::Rlcp))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PacketId {
pub(crate) layer: u32,
pub(crate) res: usize,
pub(crate) comp: usize,
pub(crate) precinct: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Step {
Point(usize),
Packet(PacketId),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Run {
Layers {
res: usize,
comp: usize,
precinct: usize,
layers: std::ops::Range<u32>,
},
Precincts {
layer: u32,
res: usize,
comp: usize,
precincts: std::ops::Range<usize>,
},
}
impl Run {
fn first(&self) -> PacketId {
match *self {
Run::Layers {
res,
comp,
precinct,
ref layers,
} => PacketId {
layer: layers.start,
res,
comp,
precinct,
},
Run::Precincts {
layer,
res,
comp,
ref precincts,
} => PacketId {
layer,
res,
comp,
precinct: precincts.start,
},
}
}
}
#[derive(Default)]
pub(crate) struct Order {
pub(crate) volumes: Vec<Volume>,
plan: Plan,
lists: Vec<PairList>,
pairs: Vec<ListRun>,
pub(crate) max_res: usize,
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Cursor {
volume: usize,
started: bool,
a: usize,
b: usize,
x: u64,
y: u64,
step: (u64, u64),
sweep: (usize, usize),
charged: bool,
item: usize,
end: usize,
inner: usize,
entered: bool,
found: Option<usize>,
}
impl Order {
pub(crate) fn heap_bytes(&self) -> usize {
use std::mem::size_of;
let lists = |outer: usize, inner: usize, item: usize| outer + inner * item;
let held = lists(
self.plan.held.capacity() * size_of::<Vec<usize>>(),
self.plan.held.iter().map(Vec::capacity).sum(),
size_of::<usize>(),
);
let pair_lists = lists(
self.lists.capacity() * size_of::<PairList>(),
self.lists.iter().map(Vec::capacity).sum(),
size_of::<(usize, usize)>(),
);
self.volumes.capacity() * size_of::<Volume>()
+ self.plan.spans.capacity() * size_of::<(Option<u64>, Option<u64>)>()
+ held
+ pair_lists
+ self.pairs.capacity() * size_of::<ListRun>()
}
pub(crate) fn new(header: &MainHeader, walk: &PacketWalk<'_>) -> Self {
let components = walk.geoms.len();
let max_res = walk.geoms.iter().map(Vec::len).max().unwrap_or(0);
let layers = u32::from(header.cod.layers);
let volumes: Vec<Volume> = if header.poc.is_empty() {
vec![Volume {
progression: header.cod.progression,
layers,
resolutions: 0..max_res,
components: 0..components,
}]
} else {
header
.poc
.iter()
.map(|v| Volume {
progression: v.progression,
layers: u32::from(v.layer_end).min(layers),
resolutions: usize::from(v.res_start)..usize::from(v.res_end).min(max_res),
components: usize::from(v.comp_start)..usize::from(v.comp_end).min(components),
})
.collect()
};
let plan = Plan::new(walk, max_res, &volumes);
let (lists, pairs) = pair_lists(&plan, components, max_res, &volumes);
Order {
volumes,
plan,
lists,
pairs,
max_res,
}
}
#[inline(always)]
fn pairs(&self, volume: usize) -> &[(usize, usize)] {
let (list, run) = &self.pairs[volume];
self.lists.get(*list).map_or(&[], |l| &l[run.clone()])
}
pub(crate) fn next(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> Option<Step> {
loop {
let volume = self.volumes.get(cursor.volume)?;
if !cursor.started {
cursor.started = true;
cursor.charged = false;
if !self.first_point(walk, cursor) {
cursor.volume += 1;
cursor.started = false;
continue;
}
}
if !cursor.charged {
cursor.charged = true;
(cursor.item, cursor.end) = self.items(cursor);
cursor.inner = 0;
cursor.entered = false;
return Some(Step::Point(1 + cursor.end - cursor.item));
}
if let Some(run) = self.next_in_point(walk, volume, cursor, false) {
return Some(Step::Packet(run.first()));
}
cursor.charged = false;
if !self.next_point(walk, cursor) {
cursor.volume += 1;
cursor.started = false;
}
}
}
#[inline(always)]
pub(crate) fn next_run(
&self,
walk: &PacketWalk<'_>,
cursor: &mut Cursor,
meter: &Meter,
) -> Result<Option<Run>> {
loop {
let Some(volume) = self.volumes.get(cursor.volume) else {
return Ok(None);
};
if !cursor.started {
cursor.started = true;
cursor.charged = false;
if !self.first_point(walk, cursor) {
cursor.volume += 1;
cursor.started = false;
continue;
}
}
if !cursor.charged {
cursor.charged = true;
(cursor.item, cursor.end) = self.items(cursor);
cursor.inner = 0;
cursor.entered = false;
meter.spend(1 + cursor.end - cursor.item, WorkRefusal::PacketWalk)?;
}
if let Some(run) = self.next_in_point(walk, volume, cursor, true) {
return Ok(Some(run));
}
let positional = !matches!(volume.progression, Progression::Lrcp | Progression::Rlcp);
if positional && self.sweep_points(walk, volume, cursor, meter)? {
continue;
}
cursor.charged = false;
let next = if positional {
self.sweep_done(walk, cursor)
} else {
self.next_point(walk, cursor)
};
if !next {
cursor.volume += 1;
cursor.started = false;
}
}
}
fn walk_runs(
&self,
walk: &PacketWalk<'_>,
meter: &Meter,
mut f: impl FnMut(u32, usize, usize, usize) -> Result<()>,
) -> Result<()> {
let mut cursor = Cursor::default();
while let Some(run) = self.next_run(walk, &mut cursor, meter)? {
match run {
Run::Layers {
res,
comp,
precinct,
layers,
} => {
for layer in layers {
f(layer, res, comp, precinct)?;
}
}
Run::Precincts {
layer,
res,
comp,
precincts,
} => {
for precinct in precincts {
f(layer, res, comp, precinct)?;
}
}
}
self.finish_point(walk, &mut cursor, &mut f)?;
}
Ok(())
}
#[inline(always)]
fn finish_point(
&self,
walk: &PacketWalk<'_>,
cursor: &mut Cursor,
f: &mut impl FnMut(u32, usize, usize, usize) -> Result<()>,
) -> Result<()> {
let Some(volume) = self.volumes.get(cursor.volume) else {
return Ok(());
};
let end = cursor.end;
match volume.progression {
Progression::Lrcp | Progression::Rlcp => {
let (layer, res) = match volume.progression {
Progression::Lrcp => (cursor.a, cursor.b),
_ => (cursor.b, cursor.a),
};
let comps = &self.plan.held[res][..end];
let mut inner = cursor.inner;
for &comp in &comps[cursor.item.min(end)..] {
for precinct in inner..walk.geoms[comp][res].precinct_count() {
f(layer as u32, res, comp, precinct)?;
}
inner = 0;
}
}
_ => {
let layers = volume.layers;
let (x, y) = (cursor.x, cursor.y);
let mut start = cursor.item;
if cursor.entered {
if let Some(precinct) = cursor.found {
let (comp, res) = self.item(volume, cursor, cursor.item);
for layer in cursor.inner as u32..layers {
f(layer, res, comp, precinct)?;
}
}
start += 1;
}
if layers > 0 {
match volume.progression {
Progression::Rpcl => {
let res = cursor.a;
for &comp in &self.plan.held[res][start.min(end)..end] {
if let Some(precinct) = walk.precinct_at(comp, res, x, y) {
for layer in 0..layers {
f(layer, res, comp, precinct)?;
}
}
}
}
_ => {
for &(comp, res) in &self.pairs(cursor.volume)[start.min(end)..end] {
if let Some(precinct) = walk.precinct_at(comp, res, x, y) {
for layer in 0..layers {
f(layer, res, comp, precinct)?;
}
}
}
}
}
}
cursor.entered = false;
}
}
cursor.item = end;
cursor.inner = 0;
Ok(())
}
#[inline(always)]
fn sweep_points(
&self,
walk: &PacketWalk<'_>,
volume: &Volume,
cursor: &mut Cursor,
meter: &Meter,
) -> Result<bool> {
let (start, end) = cursor.sweep;
let visits = 1 + end - start;
let hit = match volume.progression {
Progression::Rpcl => {
let res = cursor.a;
let comps = &self.plan.held[res][start..end];
sweep_until(walk, cursor, meter, visits, |x, y| {
comps.iter().enumerate().find_map(|(i, &comp)| {
walk.precinct_at(comp, res, x, y).map(|p| (start + i, p))
})
})?
}
_ => {
let pairs = &self.pairs(cursor.volume)[start..end];
sweep_until(walk, cursor, meter, visits, |x, y| {
pairs.iter().enumerate().find_map(|(i, &(comp, res))| {
walk.precinct_at(comp, res, x, y).map(|p| (start + i, p))
})
})?
}
};
let Some((index, precinct)) = hit else {
return Ok(false);
};
cursor.item = index;
cursor.end = end;
cursor.inner = 0;
cursor.entered = true;
cursor.found = Some(precinct);
Ok(true)
}
fn items(&self, cursor: &Cursor) -> (usize, usize) {
let volume = &self.volumes[cursor.volume];
match volume.progression {
Progression::Lrcp => self.plan.held_range(cursor.b, &volume.components),
Progression::Rlcp => self.plan.held_range(cursor.a, &volume.components),
Progression::Rpcl | Progression::Pcrl | Progression::Cprl => cursor.sweep,
}
}
#[inline(always)]
fn item(&self, volume: &Volume, cursor: &Cursor, index: usize) -> (usize, usize) {
match volume.progression {
Progression::Lrcp => (self.plan.held[cursor.b][index], cursor.b),
Progression::Rlcp | Progression::Rpcl => (self.plan.held[cursor.a][index], cursor.a),
Progression::Pcrl | Progression::Cprl => self.pairs(cursor.volume)[index],
}
}
#[inline(always)]
fn next_in_point(
&self,
walk: &PacketWalk<'_>,
volume: &Volume,
cursor: &mut Cursor,
whole: bool,
) -> Option<Run> {
if !matches!(volume.progression, Progression::Lrcp | Progression::Rlcp) {
return self.next_at_position(walk, volume, cursor, whole);
}
let res = match volume.progression {
Progression::Lrcp => cursor.b,
_ => cursor.a,
};
let layer = match volume.progression {
Progression::Lrcp => cursor.a,
_ => cursor.b,
} as u32;
while cursor.item < cursor.end {
let comp = self.plan.held[res][cursor.item];
let precincts = walk.geoms[comp][res].precinct_count();
if cursor.inner < precincts {
let start = cursor.inner;
cursor.inner = if whole { precincts } else { start + 1 };
return Some(Run::Precincts {
layer,
res,
comp,
precincts: start..cursor.inner,
});
}
cursor.inner = 0;
cursor.item += 1;
}
None
}
#[inline(always)]
fn next_at_position(
&self,
walk: &PacketWalk<'_>,
volume: &Volume,
cursor: &mut Cursor,
whole: bool,
) -> Option<Run> {
let layers = volume.layers as usize;
if cursor.entered {
if let Some(precinct) = cursor.found.filter(|_| cursor.inner < layers) {
let (comp, res) = self.item(volume, cursor, cursor.item);
let start = cursor.inner;
cursor.inner = if whole { layers } else { start + 1 };
return Some(Run::Layers {
res,
comp,
precinct,
layers: start as u32..cursor.inner as u32,
});
}
cursor.entered = false;
cursor.item += 1;
}
if layers == 0 {
cursor.item = cursor.end;
return None;
}
let (comp, res, precinct) = self.find(walk, volume, cursor, cursor.item)?;
cursor.entered = true;
cursor.found = Some(precinct);
cursor.inner = if whole { layers } else { 1 };
Some(Run::Layers {
res,
comp,
precinct,
layers: 0..cursor.inner as u32,
})
}
#[inline(always)]
fn find(
&self,
walk: &PacketWalk<'_>,
volume: &Volume,
cursor: &mut Cursor,
index: usize,
) -> Option<(usize, usize, usize)> {
let (x, y, end) = (cursor.x, cursor.y, cursor.end);
let found = match volume.progression {
Progression::Rpcl => {
let res = cursor.a;
let comps = &self.plan.held[res][..end];
(index..end).find_map(|i| {
let comp = comps[i];
walk.precinct_at(comp, res, x, y).map(|p| (i, comp, res, p))
})
}
_ => {
let pairs = &self.pairs(cursor.volume)[..end];
(index..end).find_map(|i| {
let (comp, res) = pairs[i];
walk.precinct_at(comp, res, x, y).map(|p| (i, comp, res, p))
})
}
};
match found {
Some((i, comp, res, precinct)) => {
cursor.item = i;
Some((comp, res, precinct))
}
None => {
cursor.item = end;
None
}
}
}
fn first_point(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
let volume = &self.volumes[cursor.volume];
let layers = volume.layers as usize;
let res = &volume.resolutions;
match volume.progression {
Progression::Lrcp => {
(cursor.a, cursor.b) = (0, res.start);
layers > 0 && !res.is_empty()
}
Progression::Rlcp => {
(cursor.a, cursor.b) = (res.start, 0);
layers > 0 && !res.is_empty()
}
Progression::Rpcl => {
if self.plan.step.is_none() {
return false;
}
cursor.a = res.start;
self.rpcl_resolution(walk, cursor)
}
Progression::Pcrl => {
let Some(step) = self.plan.step else {
return false;
};
cursor.step = step;
cursor.sweep = (0, self.pairs(cursor.volume).len());
cursor.sweep.1 > 0 && sweep_first(walk, cursor)
}
Progression::Cprl => {
cursor.a = 0;
self.cprl_group(walk, cursor)
}
}
}
fn next_point(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
let volume = &self.volumes[cursor.volume];
let layers = volume.layers as usize;
let res = &volume.resolutions;
match volume.progression {
Progression::Lrcp => {
cursor.b += 1;
if cursor.b < res.end {
return true;
}
cursor.b = res.start;
cursor.a += 1;
cursor.a < layers
}
Progression::Rlcp => {
cursor.b += 1;
if cursor.b < layers {
return true;
}
cursor.b = 0;
cursor.a += 1;
cursor.a < res.end
}
Progression::Rpcl | Progression::Pcrl | Progression::Cprl => {
sweep_next(walk, cursor) || self.sweep_done(walk, cursor)
}
}
}
fn sweep_done(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
match self.volumes[cursor.volume].progression {
Progression::Rpcl => {
cursor.a += 1;
self.rpcl_resolution(walk, cursor)
}
Progression::Cprl => {
cursor.a = cursor.sweep.1;
self.cprl_group(walk, cursor)
}
_ => false,
}
}
fn rpcl_resolution(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
let volume = &self.volumes[cursor.volume];
let Some(step) = self.plan.step else {
return false;
};
cursor.step = step;
while cursor.a < volume.resolutions.end {
cursor.sweep = self.plan.held_range(cursor.a, &volume.components);
if cursor.sweep.1 > cursor.sweep.0 && sweep_first(walk, cursor) {
return true;
}
cursor.a += 1;
}
false
}
fn cprl_group(&self, walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
let pairs = self.pairs(cursor.volume);
while let Some(&(comp, _)) = pairs.get(cursor.a) {
let end = cursor.a
+ pairs[cursor.a..]
.iter()
.take_while(|&&(c, _)| c == comp)
.count();
cursor.sweep = (cursor.a, end);
if let Some(step) = both(self.plan.spans[comp]) {
cursor.step = step;
if sweep_first(walk, cursor) {
return true;
}
}
cursor.a = end;
}
false
}
}
#[inline(always)]
fn sweep_until(
walk: &PacketWalk<'_>,
cursor: &mut Cursor,
meter: &Meter,
visits: usize,
mut probe: impl FnMut(u64, u64) -> Option<(usize, usize)>,
) -> Result<Option<(usize, usize)>> {
let (step_x, step_y) = cursor.step;
let (tx0, tx1) = (u64::from(walk.tile.x0), u64::from(walk.tile.x1));
let ty1 = u64::from(walk.tile.y1);
let (mut x, mut y) = (cursor.x, cursor.y);
let hit = loop {
x += step_x - (x % step_x);
if x >= tx1 {
x = tx0;
y += step_y - (y % step_y);
if y >= ty1 {
break Ok(None);
}
}
if let Err(e) = meter.spend(visits, WorkRefusal::PacketWalk) {
break Err(e);
}
if let Some(hit) = probe(x, y) {
break Ok(Some(hit));
}
};
(cursor.x, cursor.y) = (x, y);
hit
}
fn sweep_first(walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
cursor.x = u64::from(walk.tile.x0);
cursor.y = u64::from(walk.tile.y0);
cursor.x < u64::from(walk.tile.x1) && cursor.y < u64::from(walk.tile.y1)
}
fn sweep_next(walk: &PacketWalk<'_>, cursor: &mut Cursor) -> bool {
let (step_x, step_y) = cursor.step;
cursor.x += step_x - (cursor.x % step_x);
if cursor.x < u64::from(walk.tile.x1) {
return true;
}
cursor.x = u64::from(walk.tile.x0);
cursor.y += step_y - (cursor.y % step_y);
cursor.y < u64::from(walk.tile.y1)
}