Advertisement
Guest User

Untitled

a guest
Jun 5th, 2023
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 8.51 KB | None | 0 0
  1. #main.rs
  2.  
  3. use core::{ptr::NonNull, ops::{Deref, DerefMut}, marker::PhantomData, mem::transmute, mem::size_of};
  4. use core::mem::swap;
  5. use generativity::*;
  6.  
  7. pub mod weak_ref;
  8.  
  9. pub use weak_ref::weak;
  10. pub trait Promote<'a, T> {
  11.    type Output<'b> where Self : 'b;
  12.    fn promote(&self, wk : weak<'a, T>) -> &Self::Output<'a>;
  13.  
  14.    unsafe fn bind<'b>(&self, wk : weak<'b, T>) -> weak<'a, T> {
  15.         weak::from_nonnull(wk.into())
  16.     }
  17. }
  18.  
  19. trait PromoteMut<'a, T> : Promote<'a, T> {
  20.     fn promote_mut(&mut self, wk : weak<'a, T>) -> &mut Self::Output<'a>;
  21.  
  22.     fn promote_many_mut<const SIZE : usize>(&'_ mut self, ids : [weak<'a, T>; SIZE]) -> Option<[&'_ mut Self::Output<'a>; SIZE]> {
  23.         for i in 0..SIZE - 1 {
  24.             for j in i + 1..SIZE {
  25.                 if ids[i] == ids[j] {
  26.                     return None;
  27.                 }
  28.             }
  29.         }
  30.         let res = core::array::from_fn(|i| unsafe {
  31.             transmute(self.promote_mut(ids[i]))
  32.         });
  33.  
  34.         Some(res)
  35.     }
  36. }
  37.  
  38. trait IntoAnchor<'a> : Sized {
  39.    type Anchor;
  40.    fn into_anchor(self, g : Guard<'a>) -> Self::Anchor;
  41. }
  42.  
  43.  
  44. #[derive(Clone, Copy)]
  45. struct WeakIter<'a, T> {
  46.    _id : PhantomData<Id<'a>>,
  47.     current : NonNull<T>,
  48.     end : *const T
  49. }
  50.  
  51. impl <'a, T> Iterator for WeakIter<'a, T> {
  52.     type Item = weak<'a, T>;
  53.  
  54.    fn next(&mut self) -> Option<Self::Item> {
  55.        if self.current.as_ptr() as *const _ == self.end {
  56.            None
  57.        } else {
  58.            if size_of::<T>() == 0 {
  59.                let res = unsafe {
  60.                    weak::from_nonnull(NonNull::dangling())    
  61.                };
  62.                unsafe {
  63.                    self.current = NonNull::new_unchecked((self.current.as_ptr() as *mut u8).add(1) as * mut _)
  64.                }
  65.                Some(res)
  66.            } else {
  67.                let res = unsafe {
  68.                    weak::from_nonnull(self.current)    
  69.                };
  70.                unsafe {
  71.                    self.current = NonNull::new_unchecked(self.current.as_ptr().add(1));
  72.                }
  73.                Some(res)
  74.            }
  75.        }
  76.    }
  77. }
  78.  
  79. impl <'a, T> WeakIter<'a, T> {
  80.    pub fn new<'b>(src : &Anchored<'a, [T]>) -> Self {
  81.        unsafe {
  82.            if size_of::<T>() == 0 {
  83.                let current = NonNull::new_unchecked(src.as_ptr() as *mut _);
  84.                let end = (src.as_ptr() as *const u8).add(src.len()) as *const _;
  85.                WeakIter { _id: PhantomData, current, end }
  86.            } else {
  87.                let current = NonNull::new_unchecked(src.as_ptr() as *mut _);
  88.                let end = src.as_ptr().add(src.len());
  89.                WeakIter { _id: PhantomData, current, end }
  90.            }
  91.        }
  92.    }
  93. }
  94.  
  95. #[repr(transparent)]
  96. #[derive(Debug)]
  97. struct Anchored<'a, T : ?Sized> {
  98.     _id : PhantomData<Id<'a>>,
  99.    content : T
  100. }
  101. impl <'a, T : ?Sized> Anchored<'a, T> {
  102.    pub unsafe fn inner(&self) -> &T {
  103.        &self.content
  104.    }
  105.  
  106.    pub unsafe fn inner_mut(&mut self) -> &mut T {
  107.        &mut self.content
  108.    }
  109.  
  110. }
  111.  
  112. impl <'a, T> Deref for Anchored<'a, [T]> {
  113.    type Target = [T];
  114.    fn deref(&self) -> &Self::Target {
  115.        &self.content
  116.    }
  117. }
  118.  
  119. impl <'a, T> DerefMut for Anchored<'a, [T]> {
  120.    fn deref_mut(&mut self) -> &mut Self::Target {
  121.        &mut self.content
  122.    }
  123. }
  124.  
  125. impl <'a, V, T : TriviallyAnchored + ?Sized + 'a> Promote<'a, V> for Anchored<'a, T> {
  126.    type Output<'b> = V where Self : 'b;
  127.  
  128.    fn promote(&self, wk : weak<'a, V>) -> &Self::Output<'a> {
  129.        unsafe {
  130.            let ptr : NonNull<_> = wk.into();
  131.            ptr.as_ref()
  132.        }
  133.    }
  134. }
  135.  
  136. impl <'a, V, T : TriviallyAnchored + ?Sized + 'a> PromoteMut<'a, V> for Anchored<'a, T> {
  137.    fn promote_mut(&mut self, wk : weak<'a, V>) -> &mut Self::Output<'a> {
  138.        unsafe {
  139.            let mut ptr : NonNull<_> = wk.into();
  140.            ptr.as_mut()
  141.        }
  142.    }
  143. }
  144.  
  145. impl <'a, T> Anchored<'a, [T]> {
  146.    pub fn get_weak(&self, index : usize) -> Option<weak<'a, T>> {
  147.         unsafe {
  148.             self.content.get(index).map(|a| {
  149.             weak::from_nonnull(NonNull::new_unchecked(a as *const _ as *mut _))
  150.             })
  151.         }
  152.     }
  153.  
  154.     pub fn iter_weak(&self) -> WeakIter<'a, T> {
  155.        WeakIter::new(self)
  156.    }
  157. }
  158.  
  159. impl <'a, const SIZE: usize, T> Anchored<'a, [T;SIZE]> {
  160.    pub fn get_weak(&self, index : usize) -> Option<weak<'a, T>> {
  161.         unsafe {
  162.             self.content.get(index).map(|a| {
  163.                 weak::from_nonnull(NonNull::new_unchecked(a as *const _ as *mut _))
  164.             })
  165.         }
  166.     }
  167.  
  168.     pub fn iter_weak(&self) -> WeakIter<'a, T> {
  169.        WeakIter::new(self)
  170.    }
  171.  
  172. }
  173.  
  174. impl <'a, T, Array : Deref<Target = [T]>> Deref for Anchored<'a, Array> {
  175.    type Target = Anchored<'a, [T]>;
  176.  
  177.     fn deref(&self) -> &Self::Target {
  178.         unsafe {
  179.             transmute(self.inner().deref())
  180.         }
  181.     }
  182. }
  183.  
  184. impl <'a, T, Array : DerefMut<Target = [T]>> DerefMut for Anchored<'a, Array> {
  185.     fn deref_mut(&mut self) -> &mut Self::Target {
  186.         unsafe {
  187.             transmute(self.inner_mut().deref_mut())
  188.         }  
  189.     }
  190. }
  191.  
  192. pub trait TriviallyAnchored {}
  193.  
  194. impl <'this, 'a : 'this, T : TriviallyAnchored> IntoAnchor<'a> for &'this T {
  195.    type Anchor = &'this Anchored<'a, T>;
  196.  
  197.    fn into_anchor(self, _ : Guard<'a>) -> Self::Anchor {
  198.         unsafe {
  199.             transmute(self)
  200.         }
  201.     }
  202. }
  203.  
  204. impl <'this, 'a : 'this, T : TriviallyAnchored> IntoAnchor<'a> for &'this mut T {
  205.    type Anchor = &'this mut Anchored<'a, T>;
  206.  
  207.    fn into_anchor(self, _ : Guard<'a>) -> Self::Anchor {
  208.         unsafe {
  209.             transmute(self)
  210.         }
  211.     }
  212. }
  213.  
  214. impl <T> TriviallyAnchored for Vec<T> {}
  215. impl <T> TriviallyAnchored for [T] {}
  216. impl <const SIZE: usize, T> TriviallyAnchored for [T; SIZE] {}
  217.  
  218.  
  219. fn shuffle<const SIZE : usize>(data : &mut Anchored<'_, [i32; SIZE]>, random : &mut impl FnMut() -> usize) {
  220.    for (id, i) in data.iter_weak().enumerate() {
  221.        let j = id + random() % (SIZE - id);
  222.        assert!(j < SIZE);
  223.        let j = data.get_weak(j).unwrap();
  224.        if let Some([a, b]) = data.promote_many_mut([i, j]) {
  225.            swap(a, b);
  226.        }
  227.    }
  228. }
  229.  
  230. macro_rules! anchor {
  231.    ($name:ident, $src:expr) => {
  232.        make_guard!(guard);
  233.        let $name = IntoAnchor::into_anchor($src, guard);
  234.    };
  235. }
  236.  
  237. macro_rules! anchor_mut {
  238.    ($name:ident, $src:expr) => {
  239.        make_guard!(guard);
  240.        let mut $name = IntoAnchor::into_anchor($src, guard);
  241.    };
  242. }
  243.  
  244. fn main() {
  245.    let mut v0 = vec![1, 2, 3, 4];
  246.  
  247.    anchor!(v, &mut v0);
  248.  
  249.    let a = v.get_weak(0).unwrap();
  250.    let b = v.get_weak(1).unwrap();
  251.    let c = v.get_weak(3).unwrap();
  252.        
  253.    let p = v.promote(a);
  254.    dbg!(p);
  255.    dbg!(v.promote(b));
  256.    dbg!(v.promote(c));
  257.    let p = v.promote_mut(c);
  258.    *p += 3;
  259.    dbg!(v.promote(c));
  260.    
  261.    let p = v.promote_mut(c);
  262.    dbg!(v.promote(c));
  263.    
  264.    let mut random_data = [542, 3423, 45, 56, 864, 865, 75, 23, 84, 112444].into_iter();
  265.    //chosen by quantum oscillations inside the synapses of my brain.
  266.    //guaranteed to be random.
  267.  
  268.    let mut v0 = [1, 2, 3, 4];
  269.    anchor!(v, &mut v0);
  270.  
  271.    let mut random = || random_data.next().unwrap_or(0);
  272.    shuffle(v, &mut random);
  273.    dbg!(&v);
  274.  
  275.    shuffle(v, &mut random);
  276.    dbg!(&v0);
  277.  
  278. }
  279.  
  280.  
  281. # weak_ref.rs
  282. use core::marker::PhantomData;
  283. use core::ptr::NonNull;
  284. use core::hash::Hash;
  285. use core::hash::Hasher;
  286. use generativity::Id;
  287.  
  288. #[allow(non_camel_case_types)]
  289. #[repr(transparent)]
  290. #[derive(Debug)]
  291. pub struct weak<'a, T> {
  292.     _id: PhantomData<Id<'a>>,
  293.    ptr: NonNull<T>
  294. }
  295.  
  296. impl <'a, T> PartialEq for weak<'a, T> {
  297.    fn eq(&self, other: &Self) -> bool {
  298.        self.ptr == other.ptr
  299.    }
  300. }
  301.  
  302. impl <'a, T> Eq for weak<'a, T> {}
  303.  
  304. impl <'a, T> Clone for weak<'a, T> {
  305.    fn clone(&self) -> Self {
  306.        weak { _id: self._id, ptr: self.ptr }
  307.    }
  308. }
  309.  
  310. impl <'a, T> Hash for weak<'a, T> {
  311.    fn hash<H: Hasher>(&self, state: &mut H) {
  312.        self.ptr.hash(state);
  313.    }
  314. }
  315.  
  316. impl <'a, T> Copy for weak<'a, T> {}
  317.  
  318. impl <'a, T> weak<'a, T> {
  319.    pub fn unbind(self) -> weak<'static, T> {
  320.         unsafe {
  321.             weak::from_nonnull(self.into())
  322.         }
  323.     }
  324.  
  325.     pub unsafe fn from_nonnull(ptr : NonNull<T>) -> Self {
  326.         weak {
  327.             ptr,
  328.             _id : PhantomData
  329.         }
  330.     }
  331. }
  332.  
  333. impl <'a, T> Into<NonNull<T>> for weak<'a, T> {
  334.     fn into(self) -> NonNull<T> {
  335.         self.ptr
  336.     }
  337. }
  338.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement