Skip to main content

cubecl_environment/bytes/
shared_arc.rs

1//! Allocation controller that shares another [`Bytes`] through an [`Arc`].
2//!
3//! Unlike the other controllers, [`SharedAllocationController`] does not own an
4//! allocation directly. Instead it composes over an existing [`Bytes`] held
5//! behind an [`Arc`], optionally viewing only a sub-range of it. This makes
6//! cloning and splitting cheap (reference counted, zero-copy) at the cost of
7//! never being able to detach the allocation into a `Vec` (so
8//! [`Bytes::try_into_vec`](super::Bytes::try_into_vec) always fails on shared
9//! bytes).
10//!
11//! # Example
12//!
13//! ```
14//! use cubecl_environment::bytes::Bytes;
15//!
16//! let bytes = Bytes::from_elems(vec![1u32, 2, 3, 4]);
17//! let shared = bytes.shared();
18//! // Cloning is cheap, both clones reference the same backing allocation.
19//! let clone = shared.clone();
20//! assert_eq!(&shared[..], &clone[..]);
21//! ```
22
23use super::{
24    AccessError, AccessPolicy, AllocationController, AllocationProperty, Bytes, SplitError,
25    default_controller::{MAX_ALIGN, NativeAllocationController},
26};
27use crate::sync::Arc;
28use alloc::boxed::Box;
29use core::mem::MaybeUninit;
30use spin::Once;
31
32/// Allocation controller that shares a view into another [`Bytes`] behind an [`Arc`].
33///
34/// The shared content is lazily copied into a private buffer on first mutable access
35/// (copy-on-write), behind a [`Once`] so the private buffer is materialized exactly once.
36pub struct SharedAllocationController {
37    /// The shared underlying bytes.
38    inner: Arc<Bytes>,
39    /// Offset, in bytes, of this view into `inner`.
40    offset: usize,
41    /// Length, in bytes, of this view.
42    len: usize,
43    /// Lazily initialized private buffer (copy-on-write).
44    controller: Once<Box<dyn AllocationController>>,
45}
46
47impl SharedAllocationController {
48    /// Create a controller viewing `inner[offset..offset + len]`.
49    pub(crate) fn new(inner: Arc<Bytes>, offset: usize, len: usize) -> Self {
50        debug_assert!(
51            offset + len <= inner.len(),
52            "shared view must stay within the bounds of the inner bytes"
53        );
54        Self {
55            inner,
56            offset,
57            len,
58            controller: Once::new(),
59        }
60    }
61
62    /// The shared view, valid as long as no copy-on-write has occurred.
63    fn view(&self) -> &[u8] {
64        &self.inner[self.offset..self.offset + self.len]
65    }
66
67    /// Copy the shared view into a private, writable native allocation on first call.
68    /// Called lazily on first mutable access (copy-on-write).
69    fn init_mutable(&self) -> &dyn AllocationController {
70        &**self.controller.call_once(|| {
71            // Allocate with `MAX_ALIGN` to keep the data usable for any element type.
72            Box::new(
73                NativeAllocationController::alloc_with_data(self.view(), MAX_ALIGN)
74                    .expect("failed to allocate copy-on-write buffer for shared bytes"),
75            ) as Box<dyn AllocationController>
76        })
77    }
78}
79
80impl AllocationController for SharedAllocationController {
81    fn alloc_align(&self) -> usize {
82        if self.controller.is_completed() {
83            MAX_ALIGN
84        } else {
85            // Report the inner allocation's alignment. `try_into_vec` still
86            // fails because `try_detach` is never implemented for shared bytes.
87            self.inner.align()
88        }
89    }
90
91    fn property(&self) -> AllocationProperty {
92        self.inner.property()
93    }
94
95    // The view length, known without copy-on-write (never materializes).
96    fn capacity(&self) -> usize {
97        self.len
98    }
99
100    fn memory(&self, policy: AccessPolicy) -> Result<&[MaybeUninit<u8>], AccessError> {
101        match self.controller.get() {
102            // After copy-on-write, read from the private controller.
103            Some(controller) => controller.memory(policy),
104            None => {
105                // Reading the shared view is always zero-copy, so no policy check is needed.
106                let slice = self.view();
107                // SAFETY: `&[u8]` and `&[MaybeUninit<u8>]` share a layout, and every
108                // byte of the shared view is initialized.
109                Ok(unsafe { core::slice::from_raw_parts(slice.as_ptr().cast(), slice.len()) })
110            }
111        }
112    }
113
114    unsafe fn memory_mut(
115        &mut self,
116        policy: AccessPolicy,
117    ) -> Result<&mut [MaybeUninit<u8>], AccessError> {
118        // Mutating still-shared data requires copying it into a private buffer first.
119        if !self.controller.is_completed() && !policy.copy_allowed() {
120            return Err(AccessError::WouldCopy);
121        }
122        // Trigger copy-on-write so we never mutate the shared allocation.
123        self.init_mutable();
124
125        // SAFETY: `init_mutable` guarantees the private controller is set, and `&mut self` is
126        // exclusive.
127        let controller = self
128            .controller
129            .get_mut()
130            .expect("controller must be set after init_mutable");
131        unsafe { controller.memory_mut(policy) }
132    }
133
134    fn split(
135        &mut self,
136        offset: usize,
137    ) -> Result<(Box<dyn AllocationController>, Box<dyn AllocationController>), SplitError> {
138        if self.controller.is_completed() {
139            // After copy-on-write the private buffer is no longer shared.
140            return Err(SplitError::Unsupported);
141        }
142        // Use `>` (not `>=`) to allow boundary splits where one side is empty.
143        if offset > self.len {
144            return Err(SplitError::InvalidOffset);
145        }
146
147        let left = SharedAllocationController::new(self.inner.clone(), self.offset, offset);
148        let right = SharedAllocationController::new(
149            self.inner.clone(),
150            self.offset + offset,
151            self.len - offset,
152        );
153
154        Ok((Box::new(left), Box::new(right)))
155    }
156
157    fn view(&self, start: usize, end: usize) -> Option<Box<dyn AllocationController>> {
158        if self.controller.is_completed() {
159            // After copy-on-write the private buffer is no longer shared.
160            return None;
161        }
162        if start > end || end > self.len {
163            return None;
164        }
165
166        Some(Box::new(SharedAllocationController::new(
167            self.inner.clone(),
168            self.offset + start,
169            end - start,
170        )))
171    }
172
173    fn duplicate(&self) -> Option<Box<dyn AllocationController>> {
174        if self.controller.is_completed() {
175            // After mutation the private buffer can't be shared cheaply.
176            return None;
177        }
178
179        Some(Box::new(SharedAllocationController::new(
180            self.inner.clone(),
181            self.offset,
182            self.len,
183        )))
184    }
185
186    unsafe fn copy_into(&self, buf: &mut [u8]) {
187        match self.controller.get() {
188            Some(controller) => {
189                let memory = controller
190                    .memory(AccessPolicy::default())
191                    .expect("shared: host access failed");
192                let copy_len = buf.len().min(memory.len());
193                // SAFETY: every byte of the private buffer up to its length is initialized.
194                let data =
195                    unsafe { core::slice::from_raw_parts(memory.as_ptr().cast::<u8>(), copy_len) };
196                buf[..copy_len].copy_from_slice(data);
197            }
198            None => {
199                let src = self.view();
200                let copy_len = buf.len().min(src.len());
201                buf[..copy_len].copy_from_slice(&src[..copy_len]);
202            }
203        }
204    }
205}
206
207// The type is no-std; its tests need std (test_log, std collections).
208#[cfg(all(test, feature = "std"))]
209mod tests {
210    use super::super::{AccessError, Bytes, Reader, SplitPolicy, Writer};
211    use alloc::vec;
212
213    #[test_log::test]
214    fn test_shared_no_copy_write_errors_until_cow() {
215        let mut shared = Bytes::from_elems(vec![1u8, 2, 3, 4]).shared();
216
217        // Still shared: a no-copy write must refuse (it would trigger copy-on-write).
218        assert_eq!(
219            shared.write(Writer::new().no_copy()).err(),
220            Some(AccessError::WouldCopy)
221        );
222        // A no-copy *read* of shared data is always fine (zero-copy view).
223        assert_eq!(shared.read(Reader::new().no_copy()).unwrap(), &[1, 2, 3, 4]);
224
225        // A copy-allowed write triggers copy-on-write...
226        shared.write(Writer::new()).unwrap()[0] = 9;
227        // ...after which the buffer is private and a no-copy write succeeds.
228        assert!(shared.write(Writer::new().no_copy()).is_ok());
229        assert_eq!(&shared[..], &[9, 2, 3, 4]);
230    }
231
232    #[test_log::test]
233    fn test_shared_is_zero_copy_view() {
234        let bytes = Bytes::from_elems(vec![1u8, 2, 3, 4]);
235        let shared = bytes.shared();
236        assert_eq!(&shared[..], &[1, 2, 3, 4]);
237        assert_eq!(shared.len(), 4);
238    }
239
240    #[test_log::test]
241    fn test_shared_clone_is_cheap_and_equal() {
242        let shared = Bytes::from_elems(vec![10u32, 20, 30]).shared();
243        let clone = shared.clone();
244        assert_eq!(&shared[..], &clone[..]);
245    }
246
247    #[test_log::test]
248    fn test_shared_try_into_vec_never_succeeds() {
249        let shared = Bytes::from_elems(vec![1u8, 2, 3, 4]).shared();
250        assert!(shared.try_into_vec::<u8>().is_err());
251    }
252
253    #[test_log::test]
254    fn test_shared_split() {
255        let shared = Bytes::from_elems(vec![0u8, 1, 2, 3, 4, 5, 6, 7]).shared();
256        let (left, right) = shared.split(3, SplitPolicy::Shared).unwrap();
257        assert_eq!(&left[..], &[0, 1, 2]);
258        assert_eq!(&right[..], &[3, 4, 5, 6, 7]);
259    }
260
261    #[test_log::test]
262    fn test_shared_split_then_clone() {
263        let shared = Bytes::from_elems(vec![0u8, 1, 2, 3, 4, 5]).shared();
264        let (left, right) = shared.split(2, SplitPolicy::Shared).unwrap();
265        assert_eq!(&left.clone()[..], &[0, 1]);
266        assert_eq!(&right.clone()[..], &[2, 3, 4, 5]);
267    }
268
269    #[test_log::test]
270    fn test_shared_view_is_zero_copy() {
271        let shared = Bytes::from_elems(vec![0u8, 1, 2, 3, 4, 5]).shared();
272        let view = shared.view(1, 4).unwrap();
273        assert_eq!(&view[..], &[1, 2, 3]);
274        // The original is untouched and the window can't be detached into a Vec.
275        assert_eq!(&shared[..], &[0, 1, 2, 3, 4, 5]);
276        assert!(view.try_into_vec::<u8>().is_err());
277    }
278
279    #[test_log::test]
280    fn test_shared_copy_on_write() {
281        let shared = Bytes::from_elems(vec![1u8, 2, 3, 4]).shared();
282        let mut clone = shared.clone();
283        clone[0] = 99;
284
285        // The mutation is private to the clone, the original is untouched.
286        assert_eq!(&clone[..], &[99, 2, 3, 4]);
287        assert_eq!(&shared[..], &[1, 2, 3, 4]);
288    }
289
290    #[test_log::test]
291    fn test_shared_extend() {
292        let mut shared = Bytes::from_elems(vec![1u8, 2, 3]).shared();
293        shared.extend_from_byte_slice(&[4, 5, 6]);
294        assert_eq!(&shared[..], &[1, 2, 3, 4, 5, 6]);
295    }
296}