1use std::ops::{Index, IndexMut};
33
34use crate::util::point::*;
35
36#[derive(Clone, Eq, PartialEq)]
37pub struct Grid<T> {
38 pub width: i32,
39 pub height: i32,
40 pub bytes: Vec<T>,
41}
42
43impl Grid<u8> {
44 #[inline]
45 #[must_use]
46 pub fn parse(input: &str) -> Self {
47 let raw: Vec<_> = input.lines().map(str::as_bytes).collect();
48
49 let width = raw[0].len() as i32;
50 let height = raw.len() as i32;
51 let bytes = raw.concat();
52
53 Self { width, height, bytes }
54 }
55
56 #[inline]
57 #[must_use]
58 pub fn parse_with_border(input: &str) -> Self {
59 let width = input.lines().next().unwrap().len() + 1;
65 let height = input.len().div_ceil(width) + 2;
66 let size = width * height + 1;
67 let mut bytes = Vec::with_capacity(size);
68
69 bytes.resize(width + 1, b'\n');
70 bytes.extend_from_slice(input.as_bytes());
71 bytes.resize(size, b'\n');
72
73 Self { width: width as i32, height: height as i32, bytes }
74 }
75
76 pub fn print(&self) {
77 for row in self.bytes.chunks(self.width as usize) {
78 println!("{}", str::from_utf8(row).unwrap());
79 }
80 }
81}
82
83impl<T: Copy + PartialEq> Grid<T> {
84 #[inline]
85 #[must_use]
86 pub fn find(&self, needle: T) -> Option<Point> {
87 self.bytes
88 .iter()
89 .position(|&h| h == needle)
90 .map(|index| Point::new(index as i32 % self.width, index as i32 / self.width))
91 }
92}
93
94impl<T: Copy> Grid<T> {
95 #[inline]
96 #[must_use]
97 pub fn new(width: i32, height: i32, value: T) -> Self {
98 Self { width, height, bytes: vec![value; (width * height) as usize] }
99 }
100
101 #[inline]
102 #[must_use]
103 pub fn same_size_with<U: Copy>(&self, value: U) -> Grid<U> {
104 Grid::new(self.width, self.height, value)
105 }
106}
107
108impl<T> Grid<T> {
109 #[inline]
110 #[must_use]
111 pub fn contains(&self, point: Point) -> bool {
112 0 <= point.x && point.x < self.width && 0 <= point.y && point.y < self.height
113 }
114
115 #[inline]
116 #[must_use = "Iterators are lazy and do nothing unless consumed"]
117 pub fn points(&self) -> impl Iterator<Item = Point> + use<T> {
118 let (width, height) = (self.width, self.height);
119 (0..height).flat_map(move |y| (0..width).map(move |x| Point::new(x, y)))
120 }
121}
122
123impl<T> Index<Point> for Grid<T> {
124 type Output = T;
125
126 #[inline]
127 fn index(&self, index: Point) -> &Self::Output {
128 &self.bytes[(self.width * index.y + index.x) as usize]
129 }
130}
131
132impl<T> IndexMut<Point> for Grid<T> {
133 #[inline]
134 fn index_mut(&mut self, index: Point) -> &mut Self::Output {
135 &mut self.bytes[(self.width * index.y + index.x) as usize]
136 }
137}