Skip to main content

baracuda_types/
host_slice.rs

1//! [`HostSlice`] — generic abstraction over "things that are a slice of `T`".
2
3/// Trait for host-memory values that can be viewed as `&[T]`.
4///
5/// Safe-API wrappers in baracuda (and downstream crates) use this to accept
6/// any of the common host-memory containers (`&[T]`, `Vec<T>`, `Box<[T]>`,
7/// fixed-size arrays, and so on) without forcing the caller to write
8/// `.as_slice()` explicitly.
9///
10/// The blanket impl over `AsRef<[T]>` covers every standard collection out
11/// of the box. User types can implement it directly if they need custom
12/// behavior (e.g. a memory-mapped file that decodes on read).
13///
14/// # Example
15///
16/// ```
17/// use baracuda_types::HostSlice;
18///
19/// fn sum<T: core::ops::AddAssign + Default + Copy, S: HostSlice<T>>(slice: S) -> T {
20///     let mut acc = T::default();
21///     for &v in slice.as_host_slice() {
22///         acc += v;
23///     }
24///     acc
25/// }
26///
27/// assert_eq!(sum(vec![1u32, 2, 3]), 6);
28/// assert_eq!(sum([1.0f32, 2.0, 3.0]), 6.0);
29/// assert_eq!(sum(&[1i8, 2, 3][..]), 6);
30/// ```
31pub trait HostSlice<T> {
32    /// Return a slice view of the host memory.
33    fn as_host_slice(&self) -> &[T];
34
35    /// Number of elements in the slice. Default impl reads the slice length.
36    fn len(&self) -> usize {
37        self.as_host_slice().len()
38    }
39
40    /// `true` if the slice has zero elements.
41    fn is_empty(&self) -> bool {
42        self.as_host_slice().is_empty()
43    }
44}
45
46impl<T, S: AsRef<[T]> + ?Sized> HostSlice<T> for S {
47    #[inline]
48    fn as_host_slice(&self) -> &[T] {
49        self.as_ref()
50    }
51}