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
use super::*;

/// A dynamically sized span of volatile memory.
///
/// If you think of [VolBlock] as being similar to an array, this type is more
/// similar to a slice.
///
/// The primary utility of this type is just that it bundles a pointer and
/// length together, which allows you to have safe dynamic bounds checking. Just
/// like with `VolBlock`, It does **not** have a lifetime or participate in
/// borrow checking, and it does **not** enforce exclusive access.
///
/// A `VolRegion` assumes that elements of the region are directly one after the
/// other (again, like how `VolBlock` works). If you need dynamic bounds
/// checking on a spaced out series of values that would be some other type,
/// which doesn't currently exist in the library. (Open a PR maybe?)
///
/// ## Generic Parameters
/// * `T` / `R` / `W`: These parameters are applied to the [`VolAddress`] type
///   returned when accessing the region in any way (indexing, iteration, etc).
///
/// ## Safety
/// * This type stores a base [`VolAddress`] internally, and so you must follow
///   all of those safety rules. Notably, the base address must never be zero.
/// * The region must legally contain `len` contiguous values of the `T` type,
///   starting from the base address.
/// * The region must not wrap around past the end of the address space.
#[repr(C)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VolRegion<T, R, W> {
  pub(crate) addr: VolAddress<T, R, W>,
  pub(crate) len: usize,
}
impl<T, R, W> Clone for VolRegion<T, R, W> {
  #[inline]
  #[must_use]
  fn clone(&self) -> Self {
    *self
  }
}
impl<T, R, W> Copy for VolRegion<T, R, W> {}
impl<T, R, W> core::fmt::Debug for VolRegion<T, R, W> {
  #[cold]
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(f, "VolRegion<{elem_ty}, r{readability}, w{writeability}>({address:#X}, len: {len})",
      elem_ty = core::any::type_name::<T>(),
      readability=core::any::type_name::<R>(),
      writeability=core::any::type_name::<W>(),
      address=self.addr.as_usize(),
      len=self.len,
    )
  }
}
impl<T, R, W, const C: usize> From<VolBlock<T, R, W, C>>
  for VolRegion<T, R, W>
{
  #[inline]
  #[must_use]
  fn from(block: VolBlock<T, R, W, C>) -> Self {
    Self { addr: block.base, len: C }
  }
}

impl<T, R, W> VolRegion<T, R, W> {
  /// Constructs a region from raw parts.
  ///
  /// ## Safety
  /// * As per the type docs.
  #[inline]
  #[must_use]
  pub const unsafe fn from_raw_parts(
    addr: VolAddress<T, R, W>, len: usize,
  ) -> Self {
    Self { addr, len }
  }

  /// Gets the length (in elements) of the region.
  #[inline]
  #[must_use]
  #[allow(clippy::len_without_is_empty)]
  pub const fn len(self) -> usize {
    self.len
  }

  /// Converts the `VolBlock` the `usize` for the start of the block.
  #[inline]
  #[must_use]
  pub const fn as_usize(self) -> usize {
    self.addr.address.get()
  }

  /// Converts the `VolBlock` into an individual const pointer.
  ///
  /// This should usually only be used when you need to call a foreign function
  /// that expects a pointer.
  #[inline]
  #[must_use]
  pub const fn as_ptr(self) -> *const T {
    self.addr.address.get() as *const T
  }

  /// Converts the `VolBlock` into an individual mut pointer.
  ///
  /// This should usually only be used when you need to call a foreign function
  /// that expects a pointer.
  #[inline]
  #[must_use]
  pub const fn as_mut_ptr(self) -> *mut T {
    self.addr.address.get() as *mut T
  }

  /// Converts the `VolBlock` into a const slice pointer.
  #[inline]
  #[must_use]
  // TODO(2022-10-15): const fn this at some point in the future (1.64 minimum)
  pub fn as_slice_ptr(self) -> *const [T] {
    core::ptr::slice_from_raw_parts(
      self.addr.address.get() as *const T,
      self.len,
    )
  }

  /// Converts the `VolBlock` into an mut slice pointer.
  #[inline]
  #[must_use]
  // TODO(2022-10-15): const fn this at some point in the future (unstable)
  pub fn as_slice_mut_ptr(self) -> *mut [T] {
    core::ptr::slice_from_raw_parts_mut(
      self.addr.address.get() as *mut T,
      self.len,
    )
  }

  /// Index into the region.
  ///
  /// ## Panics
  /// * If the index requested is out of bounds this will panic.
  #[inline]
  #[must_use]
  #[track_caller]
  pub const fn index(self, i: usize) -> VolAddress<T, R, W> {
    assert!(i < self.len);
    unsafe { self.addr.add(i) }
  }

  /// Gets `Some(addr)` if in bounds, or `None` if out of bounds.
  #[inline]
  #[must_use]
  pub const fn get(self, i: usize) -> Option<VolAddress<T, R, W>> {
    if i < self.len {
      Some(unsafe { self.addr.add(i) })
    } else {
      None
    }
  }

  /// Gets a sub-slice of this region as a new region.
  ///
  /// ## Panics
  /// * If either specified end of the range is out of bounds this will panic.
  #[inline]
  #[must_use]
  #[track_caller]
  pub fn sub_slice<RB: core::ops::RangeBounds<usize>>(self, r: RB) -> Self {
    // TODO: some day make this a const fn, once start_bound and end_bound are
    // made into const fn, but that requires const trait impls.
    use core::ops::Bound;
    let start_inclusive: usize = match r.start_bound() {
      Bound::Included(i) => *i,
      Bound::Excluded(x) => x + 1,
      Bound::Unbounded => 0,
    };
    assert!(start_inclusive < self.len);
    let end_exclusive: usize = match r.end_bound() {
      Bound::Included(i) => i + 1,
      Bound::Excluded(x) => *x,
      Bound::Unbounded => self.len,
    };
    assert!(end_exclusive <= self.len);
    let len = end_exclusive.saturating_sub(start_inclusive);
    Self { addr: unsafe { self.addr.add(start_inclusive) }, len }
  }

  /// Gives an iterator over this region.
  #[inline]
  #[must_use]
  pub const fn iter(self) -> VolBlockIter<T, R, W> {
    VolBlockIter { base: self.addr, count: self.len }
  }

  /// Same as `region.sub_slice(range).iter()`
  #[inline]
  #[must_use]
  #[track_caller]
  pub fn iter_range<RB: core::ops::RangeBounds<usize>>(
    self, r: RB,
  ) -> VolBlockIter<T, R, W> {
    self.sub_slice(r).iter()
  }
}

impl<T, W> VolRegion<T, Safe, W>
where
  T: Copy,
{
  /// Volatile reads each element into the provided buffer.
  ///
  /// ## Panics
  /// * If the buffer's length is not *exactly* this region's length.
  #[inline]
  pub fn read_to_slice(self, buffer: &mut [T]) {
    assert_eq!(self.len, buffer.len());
    self.iter().zip(buffer.iter_mut()).for_each(|(va, s)| *s = va.read())
  }
}
impl<T, W> VolRegion<T, Unsafe, W>
where
  T: Copy,
{
  /// Volatile reads each element into the provided buffer.
  ///
  /// ## Panics
  /// * If the buffer's length is not *exactly* this region's length.
  ///
  /// ## Safety
  /// * The safety rules of reading this address depend on the device. Consult
  ///   your hardware manual.
  #[inline]
  pub unsafe fn read_to_slice(self, buffer: &mut [T]) {
    assert_eq!(self.len, buffer.len());
    self.iter().zip(buffer.iter_mut()).for_each(|(va, s)| *s = va.read())
  }
}

impl<T, R> VolRegion<T, R, Safe>
where
  T: Copy,
{
  /// Volatile all slice elements into this region.
  ///
  /// ## Panics
  /// * If the buffer's length is not *exactly* this region's length.
  #[inline]
  pub fn write_from_slice(self, buffer: &[T]) {
    assert_eq!(self.len, buffer.len());
    self.iter().zip(buffer.iter()).for_each(|(va, s)| va.write(*s))
  }
}
impl<T, R> VolRegion<T, R, Unsafe>
where
  T: Copy,
{
  /// Volatile all slice elements into this region.
  ///
  /// ## Panics
  /// * If the buffer's length is not *exactly* this region's length.
  ///
  /// ## Safety
  /// * The safety rules of writing this address depend on the device. Consult
  ///   your hardware manual.
  #[inline]
  pub unsafe fn write_from_slice(self, buffer: &[T]) {
    assert_eq!(self.len, buffer.len());
    self.iter().zip(buffer.iter()).for_each(|(va, s)| va.write(*s))
  }
}

#[test]
fn test_volregion_sub_slice() {
  let region: VolRegion<u8, Unsafe, Unsafe> =
    unsafe { VolRegion::from_raw_parts(VolAddress::new(1), 10) };
  assert_eq!(region.len, 10);

  let sub_region = region.sub_slice(..);
  assert_eq!(sub_region.len, 10);

  let sub_region = region.sub_slice(2..);
  assert_eq!(sub_region.len, 10 - 2);

  let sub_region = region.sub_slice(..3);
  assert_eq!(sub_region.len, 3);

  let sub_region = region.sub_slice(4..6);
  assert_eq!(sub_region.len, 2);
}