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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use std::{ops::RangeBounds, ptr::NonNull};
use crate::SimdVector;
/// An immutable shared subgrid of the underlying buffer.
#[derive(Debug, Copy, Clone)]
pub struct SharedSubgrid<'g, V = f32> {
ptr: NonNull<V>,
width: usize,
height: usize,
stride: usize,
_marker: std::marker::PhantomData<&'g [V]>,
}
unsafe impl<'g, V> Send for SharedSubgrid<'g, V> where &'g [V]: Send {}
unsafe impl<'g, V> Sync for SharedSubgrid<'g, V> where &'g [V]: Sync {}
impl<'g, V> From<&'g crate::AlignedGrid<V>> for SharedSubgrid<'g, V> {
fn from(value: &'g crate::AlignedGrid<V>) -> Self {
SharedSubgrid::from_buf(value.buf(), value.width(), value.height(), value.width())
}
}
impl<'g, V> SharedSubgrid<'g, V> {
/// Create a `SharedSubgrid` from raw pointer to the buffer, width, height and stride.
///
/// # Safety
/// The memory region specified by `width`, `height` and `stride` must be valid.
pub unsafe fn new(ptr: NonNull<V>, width: usize, height: usize, stride: usize) -> Self {
Self {
ptr,
width,
height,
stride,
_marker: Default::default(),
}
}
/// Create a `SharedSubgrid` from buffer slice, width, height and stride.
///
/// # Panic
/// Panics if:
/// - either `width` or `height` is zero,
/// - `width` is greater than `stride`,
/// - or the area specified by `width`, `height` and `stride` is larger than `buf`.
pub fn from_buf(buf: &'g [V], width: usize, height: usize, stride: usize) -> Self {
assert!(width > 0);
assert!(height > 0);
assert!(width <= stride);
let required_len = stride
.checked_mul(height - 1)
.and_then(|offset| offset.checked_add(width))
.expect("subgrid area overflows usize");
assert!(buf.len() >= required_len);
// SAFETY: the area is in bounds.
unsafe {
Self::new(
NonNull::new(buf.as_ptr() as *mut _).unwrap(),
width,
height,
stride,
)
}
}
/// Returns the width of the subgrid.
#[inline]
pub fn width(&self) -> usize {
self.width
}
/// Returns the height of the subgrid.
#[inline]
pub fn height(&self) -> usize {
self.height
}
#[inline]
fn try_get_ptr(&self, x: usize, y: usize) -> Option<*mut V> {
if x >= self.width || y >= self.height {
return None;
}
Some(self.get_ptr_wrapping(x, y))
}
/// Computes a raw pointer for a possibly empty subgrid boundary.
///
/// The integer offset is still checked for overflow, but pointer arithmetic is wrapping so
/// callers may construct zero-sized views whose base is outside the backing allocation. The
/// returned pointer must only be dereferenced after separately checking that it names an actual
/// element in this subgrid.
#[inline]
fn get_ptr_wrapping(&self, x: usize, y: usize) -> *mut V {
let offset = y
.checked_mul(self.stride)
.and_then(|offset| offset.checked_add(x))
.expect("subgrid offset overflows usize");
self.ptr.as_ptr().wrapping_add(offset)
}
/// Returns a reference to the sample at the given location.
///
/// # Panics
/// Panics if the coordinate is out of bounds.
#[inline]
pub fn get_ref(&self, x: usize, y: usize) -> &V {
let width = self.width;
let height = self.height;
let Some(r) = self.try_get_ref(x, y) else {
panic!("coordinate out of range: ({x}, {y}) not in {width}x{height}");
};
r
}
/// Returns a reference to the sample at the given location, or `None` if it is out of bounds.
#[inline]
pub fn try_get_ref(&self, x: usize, y: usize) -> Option<&V> {
// SAFETY: try_get_ptr returns a valid pointer.
self.try_get_ptr(x, y).map(|ptr| unsafe { &*ptr })
}
/// Returns a slice of a row of samples.
///
/// # Panics
/// Panics if the row index is out of bounds.
#[inline]
pub fn get_row(&self, row: usize) -> &[V] {
let height = self.height;
let Some(slice) = self.try_get_row(row) else {
panic!("row index out of range: height is {height} but index is {row}");
};
slice
}
/// Returns a slice of a row of samples, or `None` if it is out of bounds.
#[inline]
pub fn try_get_row(&self, row: usize) -> Option<&[V]> {
if row >= self.height {
return None;
}
if self.width == 0 {
return Some(&[]);
}
// SAFETY: row is in bounds, `width` consecutive elements from the start of a row is valid.
Some(unsafe {
let offset = row
.checked_mul(self.stride)
.expect("subgrid row offset overflows usize");
let ptr = self.ptr.as_ptr().add(offset);
std::slice::from_raw_parts(ptr as *const _, self.width)
})
}
/// Split the grid horizontally at an index.
///
/// # Panics
/// Panics if `x > self.width()`.
pub fn split_horizontal(&self, x: usize) -> (SharedSubgrid<'g, V>, SharedSubgrid<'g, V>) {
assert!(x <= self.width);
let left_ptr = self.ptr;
let right_ptr = NonNull::new(self.get_ptr_wrapping(x, 0)).unwrap();
// SAFETY: two grids are contained in `self`.
unsafe {
let left_grid = SharedSubgrid::new(left_ptr, x, self.height, self.stride);
let right_grid =
SharedSubgrid::new(right_ptr, self.width - x, self.height, self.stride);
(left_grid, right_grid)
}
}
/// Split the grid vertically at an index.
///
/// # Panics
/// Panics if `y > self.height()`.
pub fn split_vertical(&self, y: usize) -> (SharedSubgrid<'g, V>, SharedSubgrid<'g, V>) {
assert!(y <= self.height);
let top_ptr = self.ptr;
let bottom_ptr = NonNull::new(self.get_ptr_wrapping(0, y)).unwrap();
// SAFETY: two grids are contained in `self`.
unsafe {
let top_grid = SharedSubgrid::new(top_ptr, self.width, y, self.stride);
let bottom_grid =
SharedSubgrid::new(bottom_ptr, self.width, self.height - y, self.stride);
(top_grid, bottom_grid)
}
}
/// Creates a subgrid of this subgrid.
///
/// # Panics
/// Panics if the range is out of bounds.
pub fn subgrid(
&self,
range_x: impl RangeBounds<usize>,
range_y: impl RangeBounds<usize>,
) -> SharedSubgrid<'g, V> {
use std::ops::Bound;
let left = match range_x.start_bound() {
Bound::Included(&v) => v,
Bound::Excluded(&v) => v + 1,
Bound::Unbounded => 0,
};
let right = match range_x.end_bound() {
Bound::Included(&v) => v + 1,
Bound::Excluded(&v) => v,
Bound::Unbounded => self.width,
};
let top = match range_y.start_bound() {
Bound::Included(&v) => v,
Bound::Excluded(&v) => v + 1,
Bound::Unbounded => 0,
};
let bottom = match range_y.end_bound() {
Bound::Included(&v) => v + 1,
Bound::Excluded(&v) => v,
Bound::Unbounded => self.height,
};
// Bounds checks.
assert!(left <= right);
assert!(top <= bottom);
assert!(right <= self.width);
assert!(bottom <= self.height);
// SAFETY: subgrid is contained in `self`.
unsafe {
let base_ptr = NonNull::new(self.get_ptr_wrapping(left, top)).unwrap();
SharedSubgrid::new(base_ptr, right - left, bottom - top, self.stride)
}
}
}
impl<V: Copy> SharedSubgrid<'_, V> {
/// Returns a copy of sample at the given location.
///
/// # Panics
/// Panics if the coordinate is out of range.
#[inline]
pub fn get(&self, x: usize, y: usize) -> V {
*self.get_ref(x, y)
}
}
impl<'g> SharedSubgrid<'g, f32> {
/// Converts the grid to a grid of SIMD vectors, or `None` if the grid is not aligned to the
/// SIMD vector type.
///
/// # Panics
/// Panics if given SIMD vector type is not supported.
pub fn as_vectored<V: SimdVector>(&self) -> Option<SharedSubgrid<'g, V>> {
assert!(
V::available(),
"Vector type `{}` is not supported by current CPU",
std::any::type_name::<V>()
);
let mask = V::SIZE - 1;
let align_mask = std::mem::align_of::<V>() - 1;
(self.ptr.as_ptr() as usize & align_mask == 0
&& self.width & mask == 0
&& self.stride & mask == 0)
.then(|| SharedSubgrid {
ptr: self.ptr.cast::<V>(),
width: self.width / V::SIZE,
height: self.height,
stride: self.stride / V::SIZE,
_marker: Default::default(),
})
}
/// Reinterprets this subgrid as `i32` subgrid.
pub fn as_i32(&self) -> SharedSubgrid<'g, i32> {
// Safe because `f32` and `i32` has same size and align, and all bit patterns are valid.
SharedSubgrid {
ptr: self.ptr.cast(),
width: self.width,
height: self.height,
stride: self.stride,
_marker: Default::default(),
}
}
}