binius_utils/
array_2d.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright 2024 Irreducible Inc.

use bytemuck::{allocation::zeroed_vec, Zeroable};
use std::ops::{AddAssign, Deref, DerefMut, Index, IndexMut};

/// 2D array with row-major layout.
#[derive(Debug)]
pub struct Array2D<T, Data: Deref<Target = [T]> = Vec<T>> {
	data: Data,
	rows: usize,
	cols: usize,
}

impl<T: Default + Clone> Array2D<T> {
	/// Create a new 2D array of the given size initialized with default values.
	pub fn new(rows: usize, cols: usize) -> Self {
		Self {
			data: vec![T::default(); rows * cols],
			rows,
			cols,
		}
	}

	/// Create a new 2D array of the given size initialized with zeroes.
	pub fn zeroes(rows: usize, cols: usize) -> Self
	where
		T: Zeroable,
	{
		Self {
			data: zeroed_vec(rows * cols),
			rows,
			cols,
		}
	}
}

impl<T, Data: Deref<Target = [T]>> Array2D<T, Data> {
	/// Returns the number of rows in the array.
	pub fn rows(&self) -> usize {
		self.data.len() / self.cols
	}

	/// Returns the number of columns in the array.
	pub fn cols(&self) -> usize {
		self.cols
	}

	/// Returns the row at the given index.
	pub fn get_row(&self, i: usize) -> &[T] {
		let start = i * self.cols;
		&self.data[start..start + self.cols]
	}

	/// Returns an iterator over the rows of the array.
	pub fn iter_rows(&self) -> impl Iterator<Item = &[T]> {
		(0..self.rows).map(move |i| self.get_row(i))
	}

	/// Return the element at the given row and column without bounds checking.
	/// # Safety
	/// The caller must ensure that `i` and `j` are less than the number of rows and columns respectively.
	pub unsafe fn get_unchecked(&self, i: usize, j: usize) -> &T {
		self.data.get_unchecked(i * self.cols + j)
	}

	/// View of the array in a different shape, underlying elements stay the same.
	pub fn reshape(&self, rows: usize, cols: usize) -> Option<Array2D<T, &[T]>> {
		if rows * cols != self.data.len() {
			return None;
		}

		Some(Array2D {
			data: self.data.deref(),
			rows,
			cols,
		})
	}
}

impl<T, Data: DerefMut<Target = [T]>> Array2D<T, Data> {
	/// Returns the mutable row at the given index.
	pub fn get_row_mut(&mut self, i: usize) -> &mut [T] {
		let start = i * self.cols;
		&mut self.data[start..start + self.cols]
	}

	/// Return the mutable element at the given row and column without bounds checking.
	/// # Safety
	/// The caller must ensure that `i` and `j` are less than the number of rows and columns respectively.
	pub unsafe fn get_unchecked_mut(&mut self, i: usize, j: usize) -> &mut T {
		self.data.get_unchecked_mut(i * self.cols + j)
	}

	/// Mutable view of the array in a different shape, underlying elements stay the same.
	pub fn reshape_mut(&mut self, rows: usize, cols: usize) -> Option<Array2D<T, &mut [T]>> {
		if rows * cols != self.data.len() {
			return None;
		}

		Some(Array2D {
			data: self.data.deref_mut(),
			rows,
			cols,
		})
	}
}

impl<T, Data: Deref<Target = [T]>> Index<(usize, usize)> for Array2D<T, Data> {
	type Output = T;

	fn index(&self, (i, j): (usize, usize)) -> &Self::Output {
		&self.data[i * self.cols + j]
	}
}

impl<T, Data: DerefMut<Target = [T]>> IndexMut<(usize, usize)> for Array2D<T, Data> {
	fn index_mut(&mut self, (i, j): (usize, usize)) -> &mut Self::Output {
		&mut self.data[i * self.cols + j]
	}
}

impl<T: Default + Clone + AddAssign, Data: Deref<Target = [T]>> Array2D<T, Data> {
	/// Returns the sum of the elements in each row.
	pub fn sum_rows(&self) -> Vec<T> {
		let mut sum = vec![T::default(); self.cols];

		for row in self.iter_rows() {
			for (i, elem) in row.iter().enumerate() {
				sum[i] += elem.clone();
			}
		}

		sum
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_get_set() {
		let mut arr = Array2D::new(2, 3);
		arr[(0, 0)] = 1;
		arr[(0, 1)] = 2;
		arr[(0, 2)] = 3;
		arr[(1, 0)] = 4;
		arr[(1, 1)] = 5;
		arr[(1, 2)] = 6;

		assert_eq!(arr[(0, 0)], 1);
		assert_eq!(arr[(0, 1)], 2);
		assert_eq!(arr[(0, 2)], 3);
		assert_eq!(arr[(1, 0)], 4);
		assert_eq!(arr[(1, 1)], 5);
		assert_eq!(arr[(1, 2)], 6);
	}

	#[test]
	fn test_unchecked_access() {
		let mut arr = Array2D::new(2, 3);
		unsafe {
			*arr.get_unchecked_mut(0, 0) = 1;
			*arr.get_unchecked_mut(0, 1) = 2;
			*arr.get_unchecked_mut(0, 2) = 3;
			*arr.get_unchecked_mut(1, 0) = 4;
			*arr.get_unchecked_mut(1, 1) = 5;
			*arr.get_unchecked_mut(1, 2) = 6;
		}

		unsafe {
			assert_eq!(*arr.get_unchecked(0, 0), 1);
			assert_eq!(*arr.get_unchecked(0, 1), 2);
			assert_eq!(*arr.get_unchecked(0, 2), 3);
			assert_eq!(*arr.get_unchecked(1, 0), 4);
			assert_eq!(*arr.get_unchecked(1, 1), 5);
			assert_eq!(*arr.get_unchecked(1, 2), 6);
		}
	}

	#[test]
	fn test_get_row() {
		let mut arr = Array2D::new(2, 3);
		arr[(0, 0)] = 1;
		arr[(0, 1)] = 2;
		arr[(0, 2)] = 3;
		arr[(1, 0)] = 4;
		arr[(1, 1)] = 5;
		arr[(1, 2)] = 6;

		assert_eq!(arr.get_row(0), &[1, 2, 3]);
		assert_eq!(arr.get_row_mut(0), &mut [1, 2, 3]);
		assert_eq!(arr.get_row(1), &[4, 5, 6]);
		assert_eq!(arr.get_row_mut(1), &mut [4, 5, 6]);
	}

	#[test]
	fn test_sum_rows() {
		let mut arr = Array2D::new(2, 3);
		arr[(0, 0)] = 1;
		arr[(0, 1)] = 2;
		arr[(0, 2)] = 3;
		arr[(1, 0)] = 4;
		arr[(1, 1)] = 5;
		arr[(1, 2)] = 6;

		assert_eq!(arr.sum_rows(), vec![5, 7, 9]);
	}
}