eta_algorithms/data_structs/
fat_ptr.rs1#[derive(Copy, Clone)]
2pub struct FatPtrMut<T> {
3 pub ptr: *mut T,
4 pub end: *mut T,
5}
6
7impl<T> FatPtrMut<T> {
8 const SIZE: usize = std::mem::size_of::<T>();
9 #[inline(always)]
10 pub fn new(ptr: *mut T, end: *mut T) -> Self {
11 Self { ptr, end }
12 }
13
14 #[inline(always)]
15 pub fn as_slice(&self) -> &[T] {
16 let bytes_len = self.end as usize - self.ptr as usize;
17 unsafe { std::slice::from_raw_parts(self.ptr, bytes_len / Self::SIZE) }
18 }
19 #[inline(always)]
20 pub fn as_mut_slice(&mut self) -> &mut [T] {
21 let bytes_len = self.end as usize - self.ptr as usize;
22 unsafe { std::slice::from_raw_parts_mut(self.ptr, bytes_len / Self::SIZE) }
23 }
24
25 pub fn from_mut_slice(slice: &mut [T]) -> Self {
26 let ptr = slice.as_mut_ptr();
27 let end = unsafe { ptr.add(slice.len()) };
28 Self { ptr, end }
29 }
30}
31
32#[derive(Copy, Clone)]
33pub struct FatPtr<T> {
34 pub ptr: *const T,
35 pub end: *const T,
36}
37
38impl<T> FatPtr<T> {
39 const SIZE: usize = std::mem::size_of::<T>();
40 #[inline(always)]
41 pub fn new(ptr: *const T, end: *const T) -> Self {
42 Self { ptr, end }
43 }
44 #[inline(always)]
45 pub fn as_slice(&self) -> &[T] {
46 let bytes_len = self.end as usize - self.ptr as usize;
47 unsafe { std::slice::from_raw_parts(self.ptr, bytes_len / Self::SIZE) }
48 }
49
50 pub fn from_slice(slice: &[T]) -> Self {
51 let ptr = slice.as_ptr();
52 let end = unsafe { ptr.add(slice.len()) };
53 Self { ptr, end }
54 }
55}
56
57impl<T> Iterator for FatPtr<T>
58where
59 T: 'static,
60{
61 type Item = &'static T;
62 fn next(&mut self) -> Option<Self::Item> {
63 if self.ptr >= self.end {
64 return None;
65 }
66 unsafe {
67 let item = self.ptr.as_ref().unwrap();
68 self.ptr = self.ptr.offset(1);
69 Some(item)
70 }
71 }
72}
73
74impl<T> Iterator for FatPtrMut<T>
75where
76 T: 'static,
77{
78 type Item = &'static mut T;
79 fn next(&mut self) -> Option<Self::Item> {
80 if self.ptr >= self.end {
81 return None;
82 }
83 unsafe {
84 let item = self.ptr.as_mut().unwrap();
85 self.ptr = self.ptr.offset(1);
86 Some(item)
87 }
88 }
89}