///|
/// Index missing IFSC entries across all protected files, using the same global
/// slice numbers as the Reed-Solomon decoder. Values are locations, not payloads.
fn RecoverySet::fragment_sources(
  self : RecoverySet,
  missing : Array[Int32],
  candidates : Array[(String, UInt64)],
  reader : (String, UInt64, Int32) -> Bytes raise,
) -> Map[Int32, (String, UInt64)] raise {
  let found = Map([])
  if missing.is_empty() || candidates.is_empty() {
    return found
  }
  let ordered = missing.copy()
  ordered.sort()
  let targets = SliceTargets::new(self.width)
  let mut pos = 0
  let mut first = 0
  for entry in self.members {
    if pos == ordered.length() {
      break
    }
    let end = first + entry.source_slices(self.width)
    while pos < ordered.length() && ordered[pos] < end {
      let index = ordered[pos]
      let slice = index - first
      let at = slice.to_uint64() * self.width.to_uint64()
      let span = minimum(entry.length - at, self.width.to_uint64()).to_int()
      targets.add(entry, slice, span, index)
      pos = pos + 1
    }
    first = end
  }
  targets.search(candidates, reader, (i, key, at) => found[i] = (key, at))
  found
}

///|
/// Assess repair after searching additional objects for missing slices. Pass
/// current statuses from the same set and an ordered list of (key, byte length).
/// The reader receives candidate keys. The status array is left intact.
pub fn RecoverySet::plan_with_fragments(
  self : RecoverySet,
  status : Array[FileStatus],
  candidates : Array[(String, UInt64)],
  reader : (String, UInt64, Int32) -> Bytes raise,
) -> RepairPlan raise {
  let damage = self.repair_damage(status)
  let found = self.fragment_sources(damage.missing, candidates, reader)
  if found.is_empty() {
    return self.assess_damage(damage)
  }
  let missing = damage.missing.filter(i => !found.contains(i))
  self.assess_damage({ ..damage, missing, })
}