use core::fmt;
use core::ops::{BitOr, BitOrAssign};
pub const MAX_COORD: i32 = 1 << 29;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Point {
pub x: i32,
pub y: i32,
}
impl Point {
#[must_use]
pub const fn new(x: i32, y: i32) -> Self {
Self { x, y }
}
#[must_use]
pub fn manhattan(self, other: Self) -> u64 {
abs_diff(self.x, other.x) + abs_diff(self.y, other.y)
}
#[must_use]
pub fn distance_squared(self, other: Self) -> u128 {
let dx = u128::from(abs_diff(self.x, other.x));
let dy = u128::from(abs_diff(self.y, other.y));
dx * dx + dy * dy
}
#[must_use]
pub fn coordinate(self, axis: Axis) -> i32 {
match axis {
Axis::X => self.x,
Axis::Y => self.y,
}
}
#[must_use]
pub fn is_in_range(self) -> bool {
self.x.unsigned_abs() <= MAX_COORD.unsigned_abs()
&& self.y.unsigned_abs() <= MAX_COORD.unsigned_abs()
}
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
#[must_use]
pub(crate) fn abs_diff(a: i32, b: i32) -> u64 {
u64::from(a.abs_diff(b))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Axis {
X,
Y,
}
impl Axis {
#[must_use]
pub const fn other(self) -> Self {
match self {
Self::X => Self::Y,
Self::Y => Self::X,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Direction {
Right = 0,
Up = 1,
Left = 2,
Down = 3,
}
impl Direction {
pub const ALL: [Self; 4] = [Self::Right, Self::Up, Self::Left, Self::Down];
#[must_use]
pub const fn from_index(i: usize) -> Self {
Self::ALL[i % 4]
}
#[must_use]
pub const fn index(self) -> usize {
self as usize
}
#[must_use]
pub const fn reverse(self) -> Self {
Self::from_index(self.index() + 2)
}
#[must_use]
pub const fn left(self) -> Self {
Self::from_index(self.index() + 1)
}
#[must_use]
pub const fn right(self) -> Self {
Self::from_index(self.index() + 3)
}
#[must_use]
pub const fn axis(self) -> Axis {
match self {
Self::Right | Self::Left => Axis::X,
Self::Up | Self::Down => Axis::Y,
}
}
#[must_use]
pub const fn is_positive(self) -> bool {
matches!(self, Self::Right | Self::Up)
}
#[must_use]
pub const fn delta(self) -> (i32, i32) {
match self {
Self::Right => (1, 0),
Self::Up => (0, 1),
Self::Left => (-1, 0),
Self::Down => (0, -1),
}
}
#[must_use]
pub fn between(from: Point, to: Point) -> Option<Self> {
match (to.x.cmp(&from.x), to.y.cmp(&from.y)) {
(core::cmp::Ordering::Greater, core::cmp::Ordering::Equal) => Some(Self::Right),
(core::cmp::Ordering::Less, core::cmp::Ordering::Equal) => Some(Self::Left),
(core::cmp::Ordering::Equal, core::cmp::Ordering::Greater) => Some(Self::Up),
(core::cmp::Ordering::Equal, core::cmp::Ordering::Less) => Some(Self::Down),
_ => None,
}
}
#[must_use]
pub const fn turns_to(self, other: Self) -> u32 {
match (other.index() + 4 - self.index()) % 4 {
0 => 0,
2 => 2,
_ => 1,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct DirSet(u8);
impl DirSet {
pub const NONE: Self = Self(0);
pub const ALL: Self = Self(0b1111);
pub const RIGHT: Self = Self::only(Direction::Right);
pub const UP: Self = Self::only(Direction::Up);
pub const LEFT: Self = Self::only(Direction::Left);
pub const DOWN: Self = Self::only(Direction::Down);
#[must_use]
pub const fn only(dir: Direction) -> Self {
Self(1 << dir.index())
}
#[must_use]
pub const fn contains(self, dir: Direction) -> bool {
self.0 & (1 << dir.index()) != 0
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
#[must_use]
pub fn reversed(self) -> Self {
self.iter().fold(Self::NONE, |set, dir| set | dir.reverse())
}
pub fn iter(self) -> impl Iterator<Item = Direction> {
Direction::ALL
.into_iter()
.filter(move |&d| self.contains(d))
}
}
impl BitOr for DirSet {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitOr<Direction> for DirSet {
type Output = Self;
fn bitor(self, rhs: Direction) -> Self {
self | Self::only(rhs)
}
}
impl BitOrAssign for DirSet {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
impl From<Direction> for DirSet {
fn from(dir: Direction) -> Self {
Self::only(dir)
}
}
impl fmt::Debug for DirSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Side {
Right,
Top,
Left,
Bottom,
}
impl Side {
pub const ALL: [Self; 4] = [Self::Right, Self::Top, Self::Left, Self::Bottom];
#[must_use]
pub const fn outward(self) -> Direction {
match self {
Self::Right => Direction::Right,
Self::Top => Direction::Up,
Self::Left => Direction::Left,
Self::Bottom => Direction::Down,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Rect {
pub min: Point,
pub max: Point,
}
impl Rect {
#[must_use]
pub fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> Self {
Self::try_new(x0, y0, x1, y1).expect("a rectangle needs positive width and height")
}
#[must_use]
pub fn try_new(x0: i32, y0: i32, x1: i32, y1: i32) -> Option<Self> {
let min = Point::new(x0.min(x1), y0.min(y1));
let max = Point::new(x0.max(x1), y0.max(y1));
(min.x < max.x && min.y < max.y).then_some(Self { min, max })
}
#[must_use]
pub fn width(&self) -> u64 {
abs_diff(self.max.x, self.min.x)
}
#[must_use]
pub fn height(&self) -> u64 {
abs_diff(self.max.y, self.min.y)
}
#[must_use]
pub(crate) fn range(&self, axis: Axis) -> (i32, i32) {
(self.min.coordinate(axis), self.max.coordinate(axis))
}
#[must_use]
pub fn corners(&self) -> [Point; 4] {
[
self.min,
Point::new(self.max.x, self.min.y),
self.max,
Point::new(self.min.x, self.max.y),
]
}
#[must_use]
pub fn center(&self) -> Point {
Point::new(
midpoint(self.min.x, self.max.x),
midpoint(self.min.y, self.max.y),
)
}
#[must_use]
pub fn interior_contains(&self, p: Point) -> bool {
self.min.x < p.x && p.x < self.max.x && self.min.y < p.y && p.y < self.max.y
}
#[must_use]
pub fn contains(&self, p: Point) -> bool {
self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
}
#[must_use]
pub fn boundary_contains(&self, p: Point) -> bool {
self.contains(p) && !self.interior_contains(p)
}
#[must_use]
pub fn buffer(&self, amount: i32) -> Self {
Self::new(
self.min.x - amount,
self.min.y - amount,
self.max.x + amount,
self.max.y + amount,
)
}
#[must_use]
pub fn union(&self, other: &Self) -> Self {
Self {
min: Point::new(self.min.x.min(other.min.x), self.min.y.min(other.min.y)),
max: Point::new(self.max.x.max(other.max.x), self.max.y.max(other.max.y)),
}
}
#[must_use]
pub fn interiors_overlap(&self, other: &Self) -> bool {
self.min.x < other.max.x
&& other.min.x < self.max.x
&& self.min.y < other.max.y
&& other.min.y < self.max.y
}
#[must_use]
pub fn blocks_segment(&self, a: Point, b: Point) -> bool {
let (lo, hi) = (
Point::new(a.x.min(b.x), a.y.min(b.y)),
Point::new(a.x.max(b.x), a.y.max(b.y)),
);
if lo.y == hi.y {
return self.min.y < lo.y
&& lo.y < self.max.y
&& lo.x < self.max.x
&& self.min.x < hi.x;
}
self.min.x < lo.x && lo.x < self.max.x && lo.y < self.max.y && self.min.y < hi.y
}
#[must_use]
pub fn side_of(&self, p: Point) -> Option<Side> {
let on_x = p.x == self.min.x || p.x == self.max.x;
let on_y = p.y == self.min.y || p.y == self.max.y;
if !self.contains(p) || on_x == on_y {
return None;
}
Some(
match (p.x == self.max.x, p.x == self.min.x, p.y == self.max.y) {
(true, _, _) => Side::Right,
(_, true, _) => Side::Left,
(_, _, true) => Side::Top,
_ => Side::Bottom,
},
)
}
}
#[must_use]
pub(crate) fn midpoint(a: i32, b: i32) -> i32 {
i32::try_from((i64::from(a) + i64::from(b)).div_euclid(2)).expect("between two i32")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn turns_compose() {
for d in Direction::ALL {
assert_eq!(d.left().right(), d);
assert_eq!(d.left().left(), d.reverse());
assert_eq!(d.turns_to(d), 0);
assert_eq!(d.turns_to(d.left()), 1);
assert_eq!(d.turns_to(d.right()), 1);
assert_eq!(d.turns_to(d.reverse()), 2);
}
assert_eq!(Direction::Right.left(), Direction::Up);
}
#[test]
fn segment_blocking_uses_open_interior() {
let r = Rect::new(0, 0, 10, 10);
assert!(!r.blocks_segment(Point::new(-5, 0), Point::new(15, 0)));
assert!(!r.blocks_segment(Point::new(10, -5), Point::new(10, 15)));
assert!(r.blocks_segment(Point::new(-5, 5), Point::new(1, 5)));
assert!(!r.blocks_segment(Point::new(-5, 5), Point::new(0, 5)));
assert!(r.blocks_segment(Point::new(5, 20), Point::new(5, 9)));
}
#[test]
fn dirset_reverse() {
let set = DirSet::UP | Direction::Left;
assert_eq!(set.reversed(), DirSet::DOWN | Direction::Right);
assert_eq!(DirSet::ALL.iter().count(), 4);
}
#[test]
fn side_of_points() {
let r = Rect::new(0, 0, 10, 4);
assert_eq!(r.side_of(Point::new(10, 2)), Some(Side::Right));
assert_eq!(r.side_of(Point::new(3, 4)), Some(Side::Top));
assert_eq!(r.side_of(Point::new(0, 0)), None);
assert_eq!(r.side_of(Point::new(5, 2)), None);
}
}