binius_compute/
memory.rs

1// Copyright 2025 Irreducible Inc.
2
3use std::ops::RangeBounds;
4
5pub trait DevSlice<T> {
6	fn is_empty(&self) -> bool {
7		self.len() == 0
8	}
9
10	fn len(&self) -> usize;
11}
12
13impl<T> DevSlice<T> for &[T] {
14	fn len(&self) -> usize {
15		(**self).len()
16	}
17}
18
19impl<T> DevSlice<T> for &mut [T] {
20	fn len(&self) -> usize {
21		(**self).len()
22	}
23}
24
25/// Interface for manipulating handles to memory in a compute device.
26pub trait ComputeMemory<F> {
27	const MIN_SLICE_LEN: usize;
28
29	/// An opaque handle to an immutable slice of elements stored in a compute memory.
30	type FSlice<'a>: Copy + DevSlice<F>;
31
32	/// An opaque handle to a mutable slice of elements stored in a compute memory.
33	type FSliceMut<'a>: DevSlice<F>;
34
35	/// Borrows a mutable memory slice as immutable.
36	///
37	/// This allows the immutable reference to be copied.
38	fn as_const<'a>(data: &'a Self::FSliceMut<'_>) -> Self::FSlice<'a>;
39
40	/// Borrows a subslice of an immutable memory slice.
41	///
42	/// ## Preconditions
43	///
44	/// - the range bounds must be multiples of [`Self::MIN_SLICE_LEN`]
45	fn slice(data: Self::FSlice<'_>, range: impl RangeBounds<usize>) -> Self::FSlice<'_>;
46
47	/// Borrows a subslice of a mutable memory slice.
48	///
49	/// ## Preconditions
50	///
51	/// - the range bounds must be multiples of [`Self::MIN_SLICE_LEN`]
52	fn slice_mut<'a>(
53		data: &'a mut Self::FSliceMut<'_>,
54		range: impl RangeBounds<usize>,
55	) -> Self::FSliceMut<'a>;
56
57	/// Splits a mutable slice into two disjoint subslices.
58	///
59	/// ## Preconditions
60	///
61	/// - `mid` must be a multiple of [`Self::MIN_SLICE_LEN`]
62	fn split_at_mut(
63		data: Self::FSliceMut<'_>,
64		mid: usize,
65	) -> (Self::FSliceMut<'_>, Self::FSliceMut<'_>);
66
67	fn split_at_mut_borrowed<'a>(
68		data: &'a mut Self::FSliceMut<'_>,
69		mid: usize,
70	) -> (Self::FSliceMut<'a>, Self::FSliceMut<'a>) {
71		let borrowed = Self::slice_mut(data, ..);
72		Self::split_at_mut(borrowed, mid)
73	}
74}