ergo_lib_c_core/
util.rs

1//! Utility functions and types
2
3use crate::error::Error;
4
5/// Try to cast const* pointer to immutable reference.
6pub(crate) unsafe fn const_ptr_as_ref<'a, T>(
7    ptr: *const T,
8    ptr_name: &'static str,
9) -> Result<&'a T, Error> {
10    if let Some(r) = ptr.as_ref() {
11        Ok(r)
12    } else {
13        Err(Error::InvalidArgument(ptr_name))
14    }
15}
16
17/// Try to cast mut* pointer to mutable reference.
18pub(crate) unsafe fn mut_ptr_as_mut<'a, T>(
19    ptr: *mut T,
20    ptr_name: &'static str,
21) -> Result<&'a mut T, Error> {
22    if let Some(r) = ptr.as_mut() {
23        Ok(r)
24    } else {
25        Err(Error::InvalidArgument(ptr_name))
26    }
27}
28
29/// Simple wrapper around a `Vec<u8>`.
30#[derive(Clone)]
31pub struct ByteArray(pub Vec<u8>);
32pub type ByteArrayPtr = *mut ByteArray;
33pub type ConstByteArrayPtr = *const ByteArray;
34
35pub unsafe fn byte_array_from_raw_parts(
36    ptr: *const u8,
37    len: usize,
38    byte_array_out: *mut ByteArrayPtr,
39) -> Result<(), Error> {
40    let slice = std::slice::from_raw_parts(ptr, len);
41    let byte_array_out = mut_ptr_as_mut(byte_array_out, "byte_array_out")?;
42    *byte_array_out = Box::into_raw(Box::new(ByteArray(Vec::from(slice))));
43    Ok(())
44}
45
46/// Returns true iff the dereferenced pointer values are equal.
47pub unsafe fn deref_eq<T: Eq>(x_ptr: *const T, y_ptr: *const T) -> bool {
48    let x = x_ptr.as_ref().unwrap();
49    let y = y_ptr.as_ref().unwrap();
50    x == y
51}