Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unnecessary Default bound from DeviceSlice::as_host_vec. #68

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions crates/cust/src/memory/device/device_slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use bytemuck::{Pod, Zeroable};
use std::mem::{self, size_of};
use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
use std::os::raw::c_void;
use std::slice;

/// Fixed-size device-side slice.
#[derive(Debug, Copy, Clone)]
Expand All @@ -22,14 +23,6 @@ pub struct DeviceSlice<T: DeviceCopy> {
unsafe impl<T: Send + DeviceCopy> Send for DeviceSlice<T> {}
unsafe impl<T: Sync + DeviceCopy> Sync for DeviceSlice<T> {}

impl<T: DeviceCopy + Default + Clone> DeviceSlice<T> {
pub fn as_host_vec(&self) -> CudaResult<Vec<T>> {
let mut vec = vec![T::default(); self.len()];
self.copy_to(&mut vec)?;
Ok(vec)
}
}

// This works by faking a regular slice out of the device raw-pointer and the length and transmuting
// I have no idea if this is safe or not. Probably not, though I can't imagine how the compiler
// could possibly know that the pointer is not de-referenceable. I'm banking that we get proper
Expand Down Expand Up @@ -81,6 +74,17 @@ impl<T: DeviceCopy> DeviceSlice<T> {
self.ptr
}

pub fn as_host_vec(&self) -> CudaResult<Vec<T>> {
let mut vec = Vec::with_capacity(self.len());
// SAFETY: The slice points to uninitialized memory, but we only write to it. Once it is
// written, all values are valid, so we can (and must) change the length of the vector.
unsafe {
self.copy_to(slice::from_raw_parts_mut(vec.as_mut_ptr(), self.len()))?;
vec.set_len(self.len())
}
Ok(vec)
}

/* TODO (AL): keep these?
/// Divides one DeviceSlice into two at a given index.
///
Expand Down