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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! This is like the top level module, but types here are write only.

use core::{cmp::Ordering, iter::FusedIterator, marker::PhantomData, num::NonZeroUsize};
use typenum::marker_traits::Unsigned;

/// As `VolAddress`, but write only.
#[repr(transparent)]
pub struct WOVolAddress<T> {
  address: NonZeroUsize,
  marker: PhantomData<*mut T>,
}
impl<T> Clone for WOVolAddress<T> {
  fn clone(&self) -> Self {
    *self
  }
}
impl<T> Copy for WOVolAddress<T> {}
impl<T> PartialEq for WOVolAddress<T> {
  fn eq(&self, other: &Self) -> bool {
    self.address == other.address
  }
}
impl<T> Eq for WOVolAddress<T> {}
impl<T> PartialOrd for WOVolAddress<T> {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.address.cmp(&other.address))
  }
}
impl<T> Ord for WOVolAddress<T> {
  fn cmp(&self, other: &Self) -> Ordering {
    self.address.cmp(&other.address)
  }
}
impl<T> core::fmt::Debug for WOVolAddress<T> {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(f, "WOVolAddress({:p})", *self)
  }
}
impl<T> core::fmt::Pointer for WOVolAddress<T> {
  /// You can request pointer style to get _just_ the inner value with pointer
  /// formatting.
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(f, "{:p}", self.address.get() as *mut T)
  }
}
impl<T> WOVolAddress<T> {
  /// Constructs a new address.
  ///
  /// # Safety
  ///
  /// You must follow the standard safety rules as outlined in the type docs.
  pub const unsafe fn new(address: usize) -> Self {
    Self {
      address: NonZeroUsize::new_unchecked(address),
      marker: PhantomData,
    }
  }

  /// Casts the type of `T` into type `Z`.
  ///
  /// # Safety
  ///
  /// You must follow the standard safety rules as outlined in the type docs.
  pub const unsafe fn cast<Z>(self) -> WOVolAddress<Z> {
    // Note(Lokathor): This can't be `Self` because the type parameter changes.
    WOVolAddress {
      address: self.address,
      marker: PhantomData,
    }
  }

  /// Offsets the address by `offset` slots (like `pointer::wrapping_offset`).
  ///
  /// # Safety
  ///
  /// You must follow the standard safety rules as outlined in the type docs.
  pub const unsafe fn offset(self, offset: isize) -> Self {
    Self {
      address: NonZeroUsize::new_unchecked(self.address.get().wrapping_add(offset as usize * core::mem::size_of::<T>())),
      marker: PhantomData,
    }
  }

  /// Checks that the current target type of this address is aligned at this
  /// address value.
  pub const fn is_aligned(self) -> bool {
    self.address.get() % core::mem::align_of::<T>() == 0
  }

  /// The `usize` value of this `WOVolAddress`.
  pub const fn to_usize(self) -> usize {
    self.address.get()
  }

  /// Makes an iterator starting here across the given number of slots.
  ///
  /// # Safety
  ///
  /// The normal safety rules must be correct for each address iterated over.
  pub const unsafe fn iter_slots(self, slots: usize) -> WOVolIter<T> {
    WOVolIter {
      vol_address: self,
      slots_remaining: slots,
    }
  }

  /// Volatile writes a value to the address.
  ///
  /// Semantically, the value is moved into the function and then forgotten, so
  /// if `T` has a `Drop` impl then that will never get executed. This is "safe"
  /// under Rust's safety rules, but could cause something unintended (eg: a
  /// memory leak).
  pub fn write(self, val: T) {
    unsafe { (self.address.get() as *mut T).write_volatile(val) }
  }
}

/// A block of addresses all in a row, write only.
///
/// * The `C` parameter is the element count of the block.
pub struct WOVolBlock<T, C: Unsigned> {
  vol_address: WOVolAddress<T>,
  slot_count: PhantomData<C>,
}
impl<T, C: Unsigned> Clone for WOVolBlock<T, C> {
  fn clone(&self) -> Self {
    *self
  }
}
impl<T, C: Unsigned> Copy for WOVolBlock<T, C> {}
impl<T, C: Unsigned> PartialEq for WOVolBlock<T, C> {
  fn eq(&self, other: &Self) -> bool {
    self.vol_address == other.vol_address
  }
}
impl<T, C: Unsigned> Eq for WOVolBlock<T, C> {}
impl<T, C: Unsigned> core::fmt::Debug for WOVolBlock<T, C> {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(f, "WOVolBlock({:p}, count={})", self.vol_address.address.get() as *mut T, C::USIZE)
  }
}
impl<T, C: Unsigned> WOVolBlock<T, C> {
  /// Constructs a new `WOVolBlock`.
  ///
  /// # Safety
  ///
  /// The given address must be a valid `WOVolAddress` at each position in the
  /// block for however many slots (`C`).
  pub const unsafe fn new(address: usize) -> Self {
    Self {
      vol_address: WOVolAddress::new(address),
      slot_count: PhantomData,
    }
  }

  /// The length of this block (in elements)
  pub const fn len(self) -> usize {
    C::USIZE
  }

  /// Gives an iterator over the slots of this block.
  pub const fn iter(self) -> WOVolIter<T> {
    WOVolIter {
      vol_address: self.vol_address,
      slots_remaining: C::USIZE,
    }
  }

  /// Unchecked indexing into the block.
  ///
  /// # Safety
  ///
  /// The slot given must be in bounds.
  pub const unsafe fn index_unchecked(self, slot: usize) -> WOVolAddress<T> {
    self.vol_address.offset(slot as isize)
  }

  /// Checked "indexing" style access of the block, giving either a `WOVolAddress` or a panic.
  pub fn index(self, slot: usize) -> WOVolAddress<T> {
    if slot < C::USIZE {
      unsafe { self.index_unchecked(slot) }
    } else {
      panic!("Index Requested: {} >= Slot Count: {}", slot, C::USIZE)
    }
  }

  /// Checked "getting" style access of the block, giving an Option value.
  pub fn get(self, slot: usize) -> Option<WOVolAddress<T>> {
    if slot < C::USIZE {
      unsafe { Some(self.index_unchecked(slot)) }
    } else {
      None
    }
  }
}

/// A series of evenly strided addresses, write only.
///
/// * The `C` parameter is the element count of the series.
/// * The `S` parameter is the stride (in bytes) from one element to the next.
pub struct WOVolSeries<T, C: Unsigned, S: Unsigned> {
  vol_address: WOVolAddress<T>,
  slot_count: PhantomData<C>,
  stride: PhantomData<S>,
}
impl<T, C: Unsigned, S: Unsigned> Clone for WOVolSeries<T, C, S> {
  fn clone(&self) -> Self {
    *self
  }
}
impl<T, C: Unsigned, S: Unsigned> Copy for WOVolSeries<T, C, S> {}
impl<T, C: Unsigned, S: Unsigned> PartialEq for WOVolSeries<T, C, S> {
  fn eq(&self, other: &Self) -> bool {
    self.vol_address == other.vol_address
  }
}
impl<T, C: Unsigned, S: Unsigned> Eq for WOVolSeries<T, C, S> {}
impl<T, C: Unsigned, S: Unsigned> core::fmt::Debug for WOVolSeries<T, C, S> {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(
      f,
      "WOVolSeries({:p}, count={}, series={})",
      self.vol_address.address.get() as *mut T,
      C::USIZE,
      S::USIZE
    )
  }
}
impl<T, C: Unsigned, S: Unsigned> WOVolSeries<T, C, S> {
  /// Constructs a new `WOVolSeries`.
  ///
  /// # Safety
  ///
  /// The given address must be a valid `WOVolAddress` at each position in the
  /// series for however many slots (`C`), strided by the selected amount (`S`).
  pub const unsafe fn new(address: usize) -> Self {
    Self {
      vol_address: WOVolAddress::new(address),
      slot_count: PhantomData,
      stride: PhantomData,
    }
  }

  /// The length of this series (in elements)
  pub const fn len(self) -> usize {
    C::USIZE
  }

  /// Gives an iterator over the slots of this series.
  pub const fn iter(self) -> WOVolStridingIter<T, S> {
    WOVolStridingIter {
      vol_address: self.vol_address,
      slots_remaining: C::USIZE,
      stride: PhantomData,
    }
  }

  /// Unchecked indexing into the series.
  ///
  /// # Safety
  ///
  /// The slot given must be in bounds.
  pub const unsafe fn index_unchecked(self, slot: usize) -> WOVolAddress<T> {
    self.vol_address.cast::<u8>().offset((S::USIZE * slot) as isize).cast::<T>()
  }

  /// Checked "indexing" style access into the series, giving either a `WOVolAddress` or a panic.
  pub fn index(self, slot: usize) -> WOVolAddress<T> {
    if slot < C::USIZE {
      unsafe { self.index_unchecked(slot) }
    } else {
      panic!("Index Requested: {} >= Slot Count: {}", slot, C::USIZE)
    }
  }

  /// Checked "getting" style access into the series, giving an Option value.
  pub fn get(self, slot: usize) -> Option<WOVolAddress<T>> {
    if slot < C::USIZE {
      unsafe { Some(self.index_unchecked(slot)) }
    } else {
      None
    }
  }
}

/// An iterator that produces consecutive `WOVolAddress` values.
pub struct WOVolIter<T> {
  vol_address: WOVolAddress<T>,
  slots_remaining: usize,
}
impl<T> Clone for WOVolIter<T> {
  fn clone(&self) -> Self {
    Self {
      vol_address: self.vol_address,
      slots_remaining: self.slots_remaining,
    }
  }
}
impl<T> PartialEq for WOVolIter<T> {
  fn eq(&self, other: &Self) -> bool {
    self.vol_address == other.vol_address && self.slots_remaining == other.slots_remaining
  }
}
impl<T> Eq for WOVolIter<T> {}
impl<T> Iterator for WOVolIter<T> {
  type Item = WOVolAddress<T>;

  fn next(&mut self) -> Option<Self::Item> {
    if self.slots_remaining > 0 {
      let out = self.vol_address;
      unsafe {
        self.slots_remaining -= 1;
        self.vol_address = self.vol_address.offset(1);
      }
      Some(out)
    } else {
      None
    }
  }

  fn size_hint(&self) -> (usize, Option<usize>) {
    (self.slots_remaining, Some(self.slots_remaining))
  }

  fn count(self) -> usize {
    self.slots_remaining
  }

  fn last(self) -> Option<Self::Item> {
    if self.slots_remaining > 0 {
      Some(unsafe { self.vol_address.offset(self.slots_remaining as isize) })
    } else {
      None
    }
  }

  fn nth(&mut self, n: usize) -> Option<Self::Item> {
    if self.slots_remaining > n {
      // somewhere in bounds
      unsafe {
        let out = self.vol_address.offset(n as isize);
        let jump = n + 1;
        self.slots_remaining -= jump;
        self.vol_address = self.vol_address.offset(jump as isize);
        Some(out)
      }
    } else {
      // out of bounds!
      self.slots_remaining = 0;
      None
    }
  }

  fn max(self) -> Option<Self::Item> {
    self.last()
  }

  fn min(mut self) -> Option<Self::Item> {
    self.nth(0)
  }
}
impl<T> FusedIterator for WOVolIter<T> {}
impl<T> core::fmt::Debug for WOVolIter<T> {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(
      f,
      "WOVolIter({:p}, remaining={})",
      self.vol_address.address.get() as *mut T,
      self.slots_remaining
    )
  }
}

/// An iterator that produces strided `WOVolAddress` values.
pub struct WOVolStridingIter<T, S: Unsigned> {
  vol_address: WOVolAddress<T>,
  slots_remaining: usize,
  stride: PhantomData<S>,
}
impl<T, S: Unsigned> Clone for WOVolStridingIter<T, S> {
  fn clone(&self) -> Self {
    Self {
      vol_address: self.vol_address,
      slots_remaining: self.slots_remaining,
      stride: PhantomData,
    }
  }
}
impl<T, S: Unsigned> PartialEq for WOVolStridingIter<T, S> {
  fn eq(&self, other: &Self) -> bool {
    self.vol_address == other.vol_address && self.slots_remaining == other.slots_remaining
  }
}
impl<T, S: Unsigned> Eq for WOVolStridingIter<T, S> {}
impl<T, S: Unsigned> Iterator for WOVolStridingIter<T, S> {
  type Item = WOVolAddress<T>;

  fn next(&mut self) -> Option<Self::Item> {
    if self.slots_remaining > 0 {
      let out = self.vol_address;
      unsafe {
        self.slots_remaining -= 1;
        self.vol_address = self.vol_address.cast::<u8>().offset(S::ISIZE).cast::<T>();
      }
      Some(out)
    } else {
      None
    }
  }

  fn size_hint(&self) -> (usize, Option<usize>) {
    (self.slots_remaining, Some(self.slots_remaining))
  }

  fn count(self) -> usize {
    self.slots_remaining
  }

  fn last(self) -> Option<Self::Item> {
    if self.slots_remaining > 0 {
      Some(unsafe {
        self
          .vol_address
          .cast::<u8>()
          .offset(S::ISIZE * (self.slots_remaining as isize))
          .cast::<T>()
      })
    } else {
      None
    }
  }

  fn nth(&mut self, n: usize) -> Option<Self::Item> {
    if self.slots_remaining > n {
      // somewhere in bounds
      unsafe {
        let out = self.vol_address.cast::<u8>().offset(S::ISIZE * (n as isize)).cast::<T>();
        let jump = n + 1;
        self.slots_remaining -= jump;
        self.vol_address = self.vol_address.cast::<u8>().offset(S::ISIZE * (jump as isize)).cast::<T>();
        Some(out)
      }
    } else {
      // out of bounds!
      self.slots_remaining = 0;
      None
    }
  }

  fn max(self) -> Option<Self::Item> {
    self.last()
  }

  fn min(mut self) -> Option<Self::Item> {
    self.nth(0)
  }
}
impl<T, S: Unsigned> FusedIterator for WOVolStridingIter<T, S> {}
impl<T, S: Unsigned> core::fmt::Debug for WOVolStridingIter<T, S> {
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    write!(
      f,
      "WOVolStridingIter({:p}, remaining={}, stride={})",
      self.vol_address.address.get() as *mut T,
      self.slots_remaining,
      S::USIZE
    )
  }
}