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
292
293
294
295
296
297
298
299
300
use derive_more::derive::Display;
use thiserror::Error;
use unsafe_cell_slice::UnsafeCellSlice;
use zarrs_chunk_grid::iterators::{ContiguousIndices, ContiguousLinearisedIndices};
use zarrs_chunk_grid::{ArraySubset, IndexerError};
use crate::{CodecError, InvalidBytesLengthError, SubsetOutOfBoundsError};
/// A disjoint view of the bytes in an array with a fixed-length data type.
///
/// The `subset` represented by this view must not overlap with the `subset` of any other created views that reference the same array bytes.
pub struct ArrayBytesFixedDisjointView<'a> {
bytes: UnsafeCellSlice<'a, u8>,
data_type_size: usize,
shape: &'a [u64],
subset: ArraySubset,
bytes_in_subset_len: usize,
contiguous_indices: ContiguousIndices,
contiguous_linearised_indices: ContiguousLinearisedIndices,
}
/// Errors that can occur when creating a [`ArrayBytesFixedDisjointView`].
#[derive(Clone, Debug, Display, Error)]
pub enum ArrayBytesFixedDisjointViewCreateError {
/// The subset is out-of-bounds of the array shape.
SubsetOutOfBounds(#[from] SubsetOutOfBoundsError),
/// The length of the bytes is not the correct length.
InvalidBytesLength(#[from] InvalidBytesLengthError),
/// The indexer and shape are incompatible.
IndexerError(#[from] IndexerError),
}
impl From<ArrayBytesFixedDisjointViewCreateError> for CodecError {
fn from(value: ArrayBytesFixedDisjointViewCreateError) -> Self {
match value {
ArrayBytesFixedDisjointViewCreateError::SubsetOutOfBounds(e) => e.into(),
ArrayBytesFixedDisjointViewCreateError::InvalidBytesLength(e) => e.into(),
ArrayBytesFixedDisjointViewCreateError::IndexerError(e) => e.into(),
}
}
}
impl<'a> ArrayBytesFixedDisjointView<'a> {
/// Create a new non-overlapping view of the bytes in an array.
///
/// # Errors
/// Returns [`ArrayBytesFixedDisjointViewCreateError`] if
/// - `subset` is out-of-bounds of `shape`, or
/// - the length of `bytes` is not the product of the elements in `shape` multiplied by `data_type_size`.
///
/// # Safety
/// The `subset` represented by this view must not overlap with the `subset` of any other created views that reference the same array bytes.
///
/// # Panics
/// Panics if the product of the elements in `shape` multiplied by `data_type_size` exceeds [`usize::MAX`].
pub unsafe fn new(
bytes: UnsafeCellSlice<'a, u8>,
data_type_size: usize,
shape: &'a [u64],
subset: ArraySubset,
) -> Result<Self, ArrayBytesFixedDisjointViewCreateError> {
if !subset.inbounds_shape(shape) {
let bounding_subset = ArraySubset::new_with_shape(shape.to_vec());
return Err(SubsetOutOfBoundsError::new(subset, bounding_subset).into());
}
let bytes_in_array_len =
usize::try_from(shape.iter().product::<u64>()).unwrap() * data_type_size;
if bytes.len() != bytes_in_array_len {
return Err(InvalidBytesLengthError::new(bytes.len(), bytes_in_array_len).into());
}
let bytes_in_subset_len = subset.num_elements_usize() * data_type_size;
let contiguous_indices = subset.contiguous_indices(shape)?;
let contiguous_linearised_indices = subset.contiguous_linearised_indices(shape)?;
Ok(Self {
bytes,
data_type_size,
shape,
subset,
bytes_in_subset_len,
contiguous_indices,
contiguous_linearised_indices,
})
}
/// Create a new non-overlapping view of the bytes in an array that is a subset of the current view.
///
/// # Errors
/// Returns [`SubsetOutOfBoundsError`] if `subset` is out-of-bounds of the parent subset.
///
/// # Safety
/// The `subset` represented by this view must not overlap with the `subset` of any other created views that reference the same array bytes.
pub unsafe fn subdivide(
&self,
subset: ArraySubset,
) -> Result<ArrayBytesFixedDisjointView<'a>, ArrayBytesFixedDisjointViewCreateError> {
if !subset.inbounds(&self.subset) {
return Err(SubsetOutOfBoundsError::new(subset, self.subset.clone()).into());
}
unsafe { Self::new(self.bytes, self.data_type_size, self.shape, subset) }
}
/// Return the shape of the bytes this view is created from.
#[must_use]
pub fn shape(&self) -> &[u64] {
self.shape
}
/// Return the subset of the bytes this view is created from.
#[must_use]
pub fn subset(&self) -> &ArraySubset {
&self.subset
}
/// Return the number of elements in the view.
#[must_use]
pub fn num_elements(&self) -> u64 {
self.subset.num_elements()
}
/// Return the contiguous element length of the view.
///
/// This is the number of elements that are accessed in a single contiguous block.
#[must_use]
pub fn num_contiguous_elements(&self) -> usize {
self.contiguous_indices.contiguous_elements_usize()
}
/// Return the size in bytes of contiguous elements in the view.
///
/// This is the number of elements that are accessed in a single contiguous block.
#[must_use]
pub fn contiguous_bytes_len(&self) -> usize {
self.contiguous_indices.contiguous_elements_usize() * self.data_type_size
}
/// Fill the view with the fill value.
///
/// # Errors
/// Returns [`InvalidBytesLengthError`] if the length of the `fill_value` does not match the data type size.
///
/// # Panics
/// Panics if an offset into the internal bytes reference exceeds [`usize::MAX`].
pub fn fill(&mut self, fill_value: &[u8]) -> Result<(), InvalidBytesLengthError> {
if fill_value.len() != self.data_type_size {
return Err(InvalidBytesLengthError::new(
fill_value.len(),
self.data_type_size,
));
}
let fill_value_contiguous = fill_value.repeat(self.num_contiguous_elements());
let length = self.contiguous_bytes_len();
debug_assert_eq!(fill_value_contiguous.len(), length);
self.contiguous_linearised_indices
.iter()
.for_each(|(index, _contiguous_elements)| {
let offset = usize::try_from(index * self.data_type_size as u64).unwrap();
unsafe {
self.bytes
.index_mut(offset..offset + length)
.copy_from_slice(&fill_value_contiguous);
}
});
Ok(())
}
/// Copy bytes into the view.
///
/// The `subset_bytes` must be the same length as the byte length of the elements in the view.
///
/// # Errors
/// Returns an [`InvalidBytesLengthError`] if the length of `subset_bytes` is not the same as the byte length of the elements in the view.
///
/// # Panics
/// Panics if an offset into the internal bytes reference exceeds [`usize::MAX`].
pub fn copy_from_slice(&mut self, subset_bytes: &[u8]) -> Result<(), InvalidBytesLengthError> {
if subset_bytes.len() != self.bytes_in_subset_len {
return Err(InvalidBytesLengthError::new(
subset_bytes.len(),
self.bytes_in_subset_len,
));
}
let data_type_size = self.data_type_size as u64;
let bytes_copied = self.contiguous_linearised_indices.iter().fold(
0,
|subset_offset: usize,
(array_subset_element_index, contiguous_elements): (u64, u64)| {
let output_offset =
usize::try_from(array_subset_element_index * data_type_size).unwrap();
let length = usize::try_from(contiguous_elements * data_type_size).unwrap();
debug_assert!((output_offset + length) <= self.bytes.len());
debug_assert!((subset_offset + length) <= subset_bytes.len());
let subset_offset_end = subset_offset + length;
unsafe {
self.bytes
.index_mut(output_offset..output_offset + length)
.copy_from_slice(&subset_bytes[subset_offset..subset_offset_end]);
}
subset_offset_end
},
);
debug_assert_eq!(bytes_copied, subset_bytes.len());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disjoint_view() {
let mut bytes = (0..9).collect::<Vec<u8>>();
let shape = vec![3, 3];
{
let bytes = UnsafeCellSlice::new(&mut bytes);
assert!(
unsafe {
ArrayBytesFixedDisjointView::new(
bytes,
1,
&[10, 10],
ArraySubset::new_with_ranges(&[0..2, 1..3]),
)
}
.is_err()
); // incompatible shape
assert!(
unsafe {
ArrayBytesFixedDisjointView::new(
bytes,
2,
&shape,
ArraySubset::new_with_ranges(&[0..2, 1..3]),
)
}
.is_err()
); // invalid bytes length
assert!(
unsafe {
ArrayBytesFixedDisjointView::new(
bytes,
1,
&shape,
ArraySubset::new_with_ranges(&[0..2, 1..10]),
)
}
.is_err()
); // OOB
let mut view0 = unsafe {
ArrayBytesFixedDisjointView::new(
bytes,
1,
&shape,
ArraySubset::new_with_ranges(&[0..2, 1..3]),
)
}
.unwrap();
assert_eq!(view0.shape(), shape);
view0.copy_from_slice(&[11, 12, 14, 15]).unwrap();
assert!(view0.copy_from_slice(&[11, 12, 14, 15, 255]).is_err()); // wrong length
let mut view0a =
unsafe { view0.subdivide(ArraySubset::new_with_ranges(&[1..2, 1..3])) }.unwrap();
view0a.copy_from_slice(&[24, 25]).unwrap();
assert!(view0a.copy_from_slice(&[]).is_err()); // wrong length
assert!(
unsafe { view0a.subdivide(ArraySubset::new_with_ranges(&[1..2, 1..3])) }.is_ok()
);
assert!(
unsafe { view0a.subdivide(ArraySubset::new_with_ranges(&[1..2, 2..3])) }.is_ok()
);
assert!(
unsafe { view0a.subdivide(ArraySubset::new_with_ranges(&[0..2, 1..3])) }.is_err()
); // OOB
assert!(
unsafe { view0a.subdivide(ArraySubset::new_with_ranges(&[1..2, 1..4])) }.is_err()
); // OOB
let mut view1 = unsafe {
ArrayBytesFixedDisjointView::new(
bytes,
1,
&shape,
ArraySubset::new_with_ranges(&[2..3, 1..3]),
)
}
.unwrap();
view1.fill(&[255]).unwrap();
assert!(view1.fill(&[255, 255]).is_err()); // invalid fill value
}
assert_eq!(&bytes, &[0, 11, 12, 3, 24, 25, 6, 255, 255]);
}
}