1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use std::{
    cell::UnsafeCell,
    ops::{Deref, DerefMut},
};

use const_type_layout::TypeGraphLayout;
use rustacuda::{
    error::CudaResult,
    memory::{DeviceBuffer, LockedBuffer},
};

use crate::{
    alloc::{CombinedCudaAlloc, CudaAlloc, NoCudaAlloc},
    host::CudaDropWrapper,
    safety::{PortableBitSemantics, StackOnly},
    utils::{
        adapter::DeviceCopyWithPortableBitSemantics,
        ffi::{DeviceAccessible, DeviceMutPointer},
        r#async::{Async, CompletionFnMut, NoCompletion},
    },
};

use super::{common::CudaExchangeBufferCudaRepresentation, CudaExchangeItem};

#[expect(clippy::module_name_repetitions)]
pub struct CudaExchangeBufferHost<
    T: StackOnly + PortableBitSemantics + TypeGraphLayout,
    const M2D: bool,
    const M2H: bool,
> {
    host_buffer: CudaDropWrapper<
        LockedBuffer<DeviceCopyWithPortableBitSemantics<CudaExchangeItem<T, M2D, M2H>>>,
    >,
    device_buffer: UnsafeCell<
        CudaDropWrapper<
            DeviceBuffer<DeviceCopyWithPortableBitSemantics<CudaExchangeItem<T, M2D, M2H>>>,
        >,
    >,
}

impl<
        T: Clone + StackOnly + PortableBitSemantics + TypeGraphLayout,
        const M2D: bool,
        const M2H: bool,
    > CudaExchangeBufferHost<T, M2D, M2H>
{
    /// # Errors
    /// Returns a [`rustacuda::error::CudaError`] iff an error occurs inside
    /// CUDA
    pub fn new(elem: &T, capacity: usize) -> CudaResult<Self> {
        // Safety: CudaExchangeItem is a `repr(transparent)` wrapper around T
        let elem: &CudaExchangeItem<T, M2D, M2H> = unsafe { &*std::ptr::from_ref(elem).cast() };

        let host_buffer = CudaDropWrapper::from(LockedBuffer::new(
            DeviceCopyWithPortableBitSemantics::from_ref(elem),
            capacity,
        )?);
        let device_buffer = UnsafeCell::new(CudaDropWrapper::from(DeviceBuffer::from_slice(
            host_buffer.as_slice(),
        )?));

        Ok(Self {
            host_buffer,
            device_buffer,
        })
    }
}

impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    CudaExchangeBufferHost<T, M2D, M2H>
{
    /// # Errors
    /// Returns a [`rustacuda::error::CudaError`] iff an error occurs inside
    /// CUDA
    pub fn from_vec(vec: Vec<T>) -> CudaResult<Self> {
        let host_buffer = unsafe {
            let mut uninit: CudaDropWrapper<LockedBuffer<DeviceCopyWithPortableBitSemantics<_>>> =
                CudaDropWrapper::from(LockedBuffer::uninitialized(vec.len())?);

            let uninit_ptr: *mut DeviceCopyWithPortableBitSemantics<CudaExchangeItem<T, M2D, M2H>> =
                uninit.as_mut_ptr();

            for (i, src) in vec.into_iter().enumerate() {
                uninit_ptr
                    .add(i)
                    .write(DeviceCopyWithPortableBitSemantics::from(CudaExchangeItem(
                        src,
                    )));
            }

            uninit
        };

        let device_buffer = UnsafeCell::new(CudaDropWrapper::from(DeviceBuffer::from_slice(
            host_buffer.as_slice(),
        )?));

        Ok(Self {
            host_buffer,
            device_buffer,
        })
    }
}

impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool> Deref
    for CudaExchangeBufferHost<T, M2D, M2H>
{
    type Target = [CudaExchangeItem<T, M2D, M2H>];

    fn deref(&self) -> &Self::Target {
        DeviceCopyWithPortableBitSemantics::into_slice(self.host_buffer.as_slice())
    }
}

impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    DerefMut for CudaExchangeBufferHost<T, M2D, M2H>
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        DeviceCopyWithPortableBitSemantics::into_mut_slice(self.host_buffer.as_mut_slice())
    }
}

impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    CudaExchangeBufferHost<T, M2D, M2H>
{
    #[expect(clippy::type_complexity)]
    pub unsafe fn borrow<A: CudaAlloc>(
        &self,
        alloc: A,
    ) -> rustacuda::error::CudaResult<(
        DeviceAccessible<CudaExchangeBufferCudaRepresentation<T, M2D, M2H>>,
        CombinedCudaAlloc<NoCudaAlloc, A>,
    )> {
        // Safety: device_buffer is inside an UnsafeCell
        //         borrow checks must be satisfied through LendToCuda
        let device_buffer = &mut *self.device_buffer.get();

        if M2D {
            // Only move the buffer contents to the device if needed

            rustacuda::memory::CopyDestination::copy_from(
                &mut ***device_buffer,
                self.host_buffer.as_slice(),
            )?;
        }

        Ok((
            DeviceAccessible::from(CudaExchangeBufferCudaRepresentation(
                DeviceMutPointer(device_buffer.as_mut_ptr().cast()),
                device_buffer.len(),
            )),
            CombinedCudaAlloc::new(NoCudaAlloc, alloc),
        ))
    }

    pub unsafe fn restore<A: CudaAlloc>(
        &mut self,
        alloc: CombinedCudaAlloc<NoCudaAlloc, A>,
    ) -> rustacuda::error::CudaResult<A> {
        let (_alloc_front, alloc_tail) = alloc.split();

        if M2H {
            // Only move the buffer contents back to the host if needed

            rustacuda::memory::CopyDestination::copy_to(
                &***self.device_buffer.get_mut(),
                self.host_buffer.as_mut_slice(),
            )?;
        }

        Ok(alloc_tail)
    }
}

impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    CudaExchangeBufferHost<T, M2D, M2H>
{
    #[expect(clippy::type_complexity)]
    pub unsafe fn borrow_async<'stream, A: CudaAlloc>(
        &self,
        alloc: A,
        stream: crate::host::Stream<'stream>,
    ) -> rustacuda::error::CudaResult<(
        Async<'_, 'stream, DeviceAccessible<CudaExchangeBufferCudaRepresentation<T, M2D, M2H>>>,
        CombinedCudaAlloc<NoCudaAlloc, A>,
    )> {
        // Safety: device_buffer is inside an UnsafeCell
        //         borrow checks must be satisfied through LendToCuda
        let device_buffer = &mut *self.device_buffer.get();

        if M2D {
            // Only move the buffer contents to the device if needed

            rustacuda::memory::AsyncCopyDestination::async_copy_from(
                &mut ***device_buffer,
                self.host_buffer.as_slice(),
                &stream,
            )?;
        }

        let cuda_repr = DeviceAccessible::from(CudaExchangeBufferCudaRepresentation(
            DeviceMutPointer(device_buffer.as_mut_ptr().cast()),
            device_buffer.len(),
        ));

        let r#async = if M2D {
            Async::pending(cuda_repr, stream, NoCompletion)?
        } else {
            Async::ready(cuda_repr, stream)
        };

        Ok((r#async, CombinedCudaAlloc::new(NoCudaAlloc, alloc)))
    }

    #[expect(clippy::type_complexity)]
    pub unsafe fn restore_async<'a, 'stream, A: CudaAlloc, O>(
        mut this: owning_ref::BoxRefMut<'a, O, Self>,
        alloc: CombinedCudaAlloc<NoCudaAlloc, A>,
        stream: crate::host::Stream<'stream>,
    ) -> rustacuda::error::CudaResult<(
        Async<'a, 'stream, owning_ref::BoxRefMut<'a, O, Self>, CompletionFnMut<'a, Self>>,
        A,
    )> {
        let (_alloc_front, alloc_tail) = alloc.split();

        if M2H {
            // Only move the buffer contents back to the host if needed

            let this: &mut Self = &mut this;

            rustacuda::memory::AsyncCopyDestination::async_copy_to(
                &***this.device_buffer.get_mut(),
                this.host_buffer.as_mut_slice(),
                &stream,
            )?;
        }

        let r#async = if M2H {
            Async::<_, CompletionFnMut<'a, Self>>::pending(this, stream, Box::new(|_this| Ok(())))?
        } else {
            Async::ready(this, stream)
        };

        Ok((r#async, alloc_tail))
    }
}