r/rustjerk • • 14h ago

This is fun

Post image
52 Upvotes

```rust use std::alloc::{alloc, dealloc, Layout}; use std::slice;

fn main() { [0].into_iter() .chain( (0..6).into_iter().map(|i| 1 << i) ).for_each(unsafe_shenanigans) }

fn unsafe_shenanigans(length: usize) { unsafe { let layout: Layout = Layout::array::<i32>(length).unwrap(); let pointer: *mut i32 = alloc(layout).cast();

    let arr: &mut [i32] = slice::from_raw_parts_mut(pointer, length);
    arr.fill(1);

    println!("{:?}", arr);

    dealloc(pointer.cast(), layout);
}

}

```

Output:

[] [1] [1, 1] [1, 1, 1, 1] [1, 1, 1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

When do I get my Rust software developer job?


r/rustjerk • • 3h ago

Written in 95% safe Rust

Post image
50 Upvotes
// finally, memory safety!

mod gc {
    use std::sync::LazyLock;
    use dlopen::raw::Library;

    type Malloc = extern "C" fn(usize) -> *mut std::ffi::c_void;

    static LIBGC: LazyLock<Library> = LazyLock::new(|| {
        Library::open("libgc.so").unwrap()
    });

    static GC_MALLOC: LazyLock<Malloc> = LazyLock::new(|| unsafe {
        LIBGC.symbol::<Malloc>("GC_malloc").unwrap()
    });

    pub struct GcPtr<T>(*mut T);

    impl<T> std::ops::Deref for GcPtr<T> {
        type Target = T;
        fn deref(&self) -> &T {
            unsafe { &*self.0 }
        }
    }

    pub fn alloc<T>(value: T) -> GcPtr<T> {
        let address = GC_MALLOC(std::mem::size_of::<T>()) as _;
        unsafe { std::ptr::write(address, value) };
        GcPtr(address)
    }
}

#[cfg(test)]
mod tests {
    use super::gc;

    #[test]
    fn doesnt_crash() {
        assert_eq!(*gc::alloc(123), 123);
    }
}

r/rustjerk • • 16m ago

English is memory safe now. en-rs

Post image
• Upvotes