Advertisement
Guest User

Variable length array

a guest
May 16th, 2025
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.83 KB | Software | 0 0
  1. impl VLACtx{
  2.     /**
  3.      * Create the context for the VLA.
  4.      *
  5.      * **Note** Unless you know what you are doing use the `vlam::ctx!` macro
  6.      *
  7.      * **Safety** The function is unsafe because it produces a VLACtx that is not protected by a pin
  8.      * which means it can be moved outside the scope that makes it valid. Moving VLA will lead to UB.
  9.      */
  10.     #[inline(always)]
  11.     pub unsafe fn init() -> Self{
  12.         let mut saved_sp = null();
  13.  
  14.         // SAFETY : This only save a frame pointer
  15.         unsafe {
  16.             core::arch::asm!(
  17.             "mv {saved_sp}, sp",
  18.             saved_sp = out(reg) saved_sp,
  19.             )
  20.         };
  21.  
  22.         VLACtx{saved_sp, phantom_pinned: Default::default() }
  23.     }
  24.  
  25.     /**
  26.      * Create a buffer of `len` bytes initialized at 0
  27.      */
  28.     #[inline(always)]
  29.     pub fn zeroed_buffer<'ctx>(self: &'ctx Pin<&'ctx mut Self>, len:usize) -> VLArray<'ctx, u8> {
  30.         let mut origin: *mut u8 = null_mut();
  31.         unsafe {
  32.             let len = len * size_of::<u8>();
  33.             let len = (len / MIN_ALIGN + 1) * MIN_ALIGN;
  34.             asm!(
  35.             "mv {orig}, sp",
  36.             "sub sp, sp, {len}",
  37.             orig = out(reg) origin,
  38.             len = in(reg) len
  39.             );
  40.  
  41.             origin = origin.sub(len);
  42.             write_bytes(origin, 0, len);
  43.         }
  44.  
  45.         VLArray{
  46.             ptr:origin,
  47.             len,
  48.             _ctx: self,
  49.         }
  50.     }
  51.  
  52.  
  53. }
  54.  
  55. impl Drop for VLACtx{
  56.     #[inline(always)]
  57.     fn drop(&mut self) {
  58.         let saved_sp  = self.saved_sp;
  59.         // SAFETY: Restores the stack pointer.
  60.         // This is only safe because the type is pinned to the stack at all time.
  61.         unsafe {
  62.             asm!(
  63.             "mv sp, {saved_sp}",
  64.             saved_sp = in(reg) saved_sp,
  65.             )
  66.         };
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement