1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#![allow(dead_code)]

use std::{os::raw::c_void, ptr::NonNull};
pub struct HyVoid<T> {
    ptr: *mut T,
}
unsafe impl<T> Send for HyVoid<T> where T: Send {}
unsafe impl<T> Sync for HyVoid<T> where T: Sync {}

impl<T> HyVoid<T> {
    pub fn from_ref(r: &mut T) -> Self {
        Self {
            ptr: NonNull::from(r).as_ptr().cast(),
        }
    }
    pub fn from_ptr(ptr: *mut c_void) -> Self {
        Self { ptr: ptr.cast() }
    }

    pub fn as_ptr(&self) -> *mut c_void {
        self.ptr.cast()
    }
    pub fn as_dptr(&mut self) -> *mut *mut c_void {
        std::ptr::addr_of_mut!(self.ptr).cast()
    }
}

pub struct HyVoidConst<T> {
    ptr: *const T,
}
unsafe impl<T> Send for HyVoidConst<T> where T: Send {}
unsafe impl<T> Sync for HyVoidConst<T> where T: Sync {}

impl<T> HyVoidConst<T> {
    pub fn from_ref(r: &T) -> Self {
        Self {
            ptr: NonNull::from(r).as_ptr().cast(),
        }
    }
    pub fn from_ptr(ptr: *const c_void) -> Self {
        Self { ptr: ptr.cast() }
    }

    pub fn as_ptr(&self) -> *const c_void {
        self.ptr.cast()
    }
    pub fn as_dptr(&mut self) -> *const *const c_void {
        std::ptr::addr_of!(self.ptr).cast()
    }
}

pub fn opacue_to_mut<'a, T>(user: *mut T) -> &'a mut T {
    if user.is_null() {
        panic!("Pointer is null")
    }
    unsafe { &mut *(user.cast()) as &mut T }
}
pub fn opacue_to_ref<'a, T>(user: *const T) -> &'a T {
    unsafe { &*(user.cast()) as &T }
}

pub fn of_addr<'a, T>(user: *const T) -> &'a T {
    opacue_to_ref(user)
}

pub fn of_mut_addr<'a, T>(user: *mut T) -> &'a mut T {
    opacue_to_mut(user)
}
pub fn mut_to_opacue<T>(r: &mut T) -> *mut c_void {
    r as *const _ as *mut _
}

pub fn delete<T>(ctx: *mut c_void) {
    drop(unsafe { Box::from_raw(ctx as *mut _ as *mut T) });
}
pub fn new<T>(t: T) -> *mut c_void {
    unsafe { &mut *(Box::into_raw(Box::new(t)) as *mut c_void) }
}

pub fn new_and_then<T, F>(t: T, op: F) -> Result<*mut c_void, anyhow::Error>
where
    F: FnOnce(&mut T) -> Result<(), anyhow::Error>,
{
    let mut b = Box::new(t);

    match op(b.as_mut()) {
        Ok(_) => Ok(unsafe { &mut *(Box::into_raw(b) as *mut c_void) }),
        Err(e) => Err(e),
    }
}