How can I robustly make (unknown) tables span the full page width?

For future reference this is the binary search for typst.

It speeds up Andrew’s test document significantly, even if it’s small. Since it might be useful in some other settings, there’s a test function that travels with this code… And yes, this is partition point, the simplified version of bisection that we need.

/// Get index of partition point
/// - func (function): Return true if less or equal, false if greater than partition point
// based on rust libcore partition point
#let partition-point(range, func) = {
  let size = range.len()
  if size == 0 {
    panic("Empty range in partition-point")
  }
  let base = 0
  while size > 1 {
    let half = calc.div-euclid(size, 2)
    let mid = base + half
    let lte = func(range.at(mid))
    base = if lte { mid } else { base }
    size -= half
  }
  let lte = func(range.at(base))
  base + int(lte)
}

#let test-partition(arr, func) = {
  let partition(arr, i) = (arr.slice(0, i), arr.slice(i, none))
  let pp = partition-point(arr, func)
  [pp=#pp: ]
  let (low, high) = partition(arr, pp)
  repr((low, high))
  assert(low.all(elt => func(elt)))
  assert(high.all(elt => not func(elt)))
}

// #test-partition(range(10), elt => elt <= 4)
// #test-partition(range(10, step: 2), elt => elt <= 5)

#let estimate-min-width(doc) = {
  let nominal-length = measure(doc).width
  let ceil = calc.ceil(nominal-length.pt())
  let widths = range(ceil, step: 1)
  let pp = partition-point(widths, w => {
    let max-width = w * 1pt
    let actual-width = measure(doc, width: max-width).width
    not (actual-width < max-width)
  })
  let min-step = widths.at(pp, default: ceil) * 1pt
  let min-width = measure(doc, width: min-step).width
  return min-width
}
1 Like