Skip to content
This repository has been archived by the owner on Mar 28, 2022. It is now read-only.

Commit

Permalink
Add void_cast_slice
Browse files Browse the repository at this point in the history
  • Loading branch information
termoshtt committed Mar 22, 2018
1 parent 88ab4fd commit 3cd7f12
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,55 @@ impl<'m> Kernel<'m> {
}

/// Get type-erased pointer
pub fn void_cast<T>(r: &T) -> *mut c_void {
///
/// ```
/// # use accel::kernel::void_cast;
/// let a = 1_usize;
/// let p = void_cast(&a);
/// unsafe { assert_eq!(*(p as *mut usize), 1) };
/// ```
///
/// This returns the pointer for slice, and the length of slice is dropped:
///
/// ```
/// # use accel::kernel::void_cast;
/// # use std::os::raw::c_void;
/// let s: &[f64] = &[0.0; 4];
/// let p = s.as_ptr() as *mut c_void;
/// let p1 = void_cast(s);
/// let p2 = void_cast(&s);
/// assert_eq!(p, p1);
/// assert_ne!(p, p2); // Result of slice and &slice are different!
/// ```
pub fn void_cast<T: ?Sized>(r: &T) -> *mut c_void {
&*r as *const T as *mut c_void
}

/// Representaion of `core::slice`
#[repr(C)]
pub struct SliceRepr<T> {
pub data: *const T,
pub len: usize,
}

/// Get type-erased slice
///
/// ```
/// # use accel::kernel::*;
/// # use std::os::raw::c_void;
/// let s: &[f64] = &[0.0; 4];
/// let p = s.as_ptr() as *mut c_void;
/// let p1 = void_cast_slice(s);
/// assert_ne!(p, p1);
/// let repr = unsafe { &*(p1 as *mut SliceRepr<usize>) };
/// assert_eq!(p, repr.data as *mut c_void);
/// assert_eq!(repr.len, 4);
/// ```
pub fn void_cast_slice<T>(r: &[T]) -> *mut c_void {
let r = unsafe { ::std::mem::transmute::<_, SliceRepr<T>>(r) };
&r as *const SliceRepr<T> as *mut _
}

/// Size of Block (thread block) in [CUDA thread hierarchy]( http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#programming-model )
#[derive(Debug, Clone, Copy, NewType)]
pub struct Block(dim3);
Expand Down

0 comments on commit 3cd7f12

Please sign in to comment.