nya-core 0.2.0

nya core library
Documentation
//! Memory manipulation

// TODO: come up with better name for [reinterpret] and [reinterpret_mut]

/// Reinterpret pointer `T` as reference to a `C`
///
/// This should be useful in FFI when given an opaque pointer.
///
/// # Safety
///
/// Breaks borrow checker rules
pub unsafe fn reinterpret<T, C>(ptr: *const T) -> &'static C {
    unsafe { &*(ptr as *const C) }
}

/// Reinterpret pointer `T` as mutable reference to a `C`, see [reinterpret]
///
/// # Safety
///
/// Breaks borrow checker rules
pub unsafe fn reinterpret_mut<T, C>(ptr: *mut T) -> &'static mut C {
    unsafe { &mut *(ptr as *mut C) }
}

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

    #[test]
    fn reinterpret_test() {
        let j = 3;
        let p = (&j) as *const i32;

        unsafe {
            let y: &mut f32 = reinterpret_mut(p as *mut f32);
            *y = 43.0;
            println!("{} {}", *p, y);
        }
    }
}