This commit is contained in:
numbers
2023-09-25 20:55:37 -04:00
parent 694004ecfa
commit 865e7b070e
3 changed files with 65 additions and 6 deletions

View File

@@ -38,4 +38,49 @@ pub fn distance(p1: impl IntoUsize, p2: impl IntoUsize) -> usize {
Ordering::Greater => p1 - p2,
Ordering::Equal => 0,
}
}
}
mod pointer_iterator {
pub trait Pointer {
type IterType;
fn into_iter(self) -> Self::IterType;
}
pub struct PIter<T>(*const T);
pub struct PIterMut<T>(*mut T);
impl<T: 'static> Iterator for PIter<T> {
type Item = &'static T;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let r = Some(&*self.0);
self.0 = self.0.offset(1isize);
r
}
}
}
impl<T: 'static> Iterator for PIterMut<T> {
type Item = &'static mut T;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let r = Some(&mut *self.0);
self.0 = self.0.offset(1isize);
r
}
}
}
impl<T> Pointer for *const T {
type IterType = PIter<T>;
fn into_iter(self) -> Self::IterType { PIter(self) }
}
impl<T> Pointer for *mut T {
type IterType = PIterMut<T>;
fn into_iter(self) -> Self::IterType { PIterMut(self) }
}
}
pub fn iterate<T: pointer_iterator::Pointer>(pointer: T) -> T::IterType {
pointer.into_iter()
}