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
#[cfg(not(target_os = "cuda"))]
use core::iter::Iterator;

use const_type_layout::TypeGraphLayout;
use rust_cuda::{
    safety::{PortableBitSemantics, SafeMutableAliasing, StackOnly},
    utils::{
        aliasing::SplitSliceOverCudaThreadsConstStride,
        exchange::buffer::{CudaExchangeBuffer, CudaExchangeItem},
    },
};

#[cfg(not(target_os = "cuda"))]
use rust_cuda::deps::rustacuda::{
    error::CudaResult,
    function::{BlockSize, GridSize},
};

use super::utils::MaybeSome;

#[derive(rust_cuda::lend::LendRustToCuda)]
#[cuda(free = "T")]
#[allow(clippy::module_name_repetitions)]
pub struct ValueBuffer<T, const M2D: bool, const M2H: bool>
where
    T: StackOnly + PortableBitSemantics + TypeGraphLayout,
{
    #[cuda(embed)]
    mask: SplitSliceOverCudaThreadsConstStride<CudaExchangeBuffer<bool, true, true>, 1_usize>,
    #[cuda(embed)]
    buffer:
        SplitSliceOverCudaThreadsConstStride<CudaExchangeBuffer<MaybeSome<T>, M2D, M2H>, 1_usize>,
}

// Safety:
// - no mutable aliasing occurs since all parts implement SafeMutableAliasing
// - dropping does not trigger (de)alloc since ValueBuffer doesn't impl Drop and
//   all parts implement SafeMutableAliasing
// - ValueBuffer has no shallow mutable state
unsafe impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    SafeMutableAliasing for ValueBuffer<T, M2D, M2H>
where
    SplitSliceOverCudaThreadsConstStride<CudaExchangeBuffer<bool, true, true>, 1_usize>:
        SafeMutableAliasing,
    SplitSliceOverCudaThreadsConstStride<CudaExchangeBuffer<MaybeSome<T>, M2D, M2H>, 1_usize>:
        SafeMutableAliasing,
{
}

#[cfg(not(target_os = "cuda"))]
impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool, const M2H: bool>
    ValueBuffer<T, M2D, M2H>
{
    /// # Errors
    /// Returns a `rustacuda::errors::CudaError` iff an error occurs inside CUDA
    pub fn new(block_size: &BlockSize, grid_size: &GridSize) -> CudaResult<Self> {
        let block_size = (block_size.x * block_size.y * block_size.z) as usize;
        let grid_size = (grid_size.x * grid_size.y * grid_size.z) as usize;
        let total_capacity = block_size * grid_size;

        let mut buffer = alloc::vec::Vec::with_capacity(total_capacity);
        buffer.resize_with(total_capacity, || MaybeSome::None);

        Ok(Self {
            mask: SplitSliceOverCudaThreadsConstStride::new(CudaExchangeBuffer::new(
                &false,
                total_capacity,
            )?),
            buffer: SplitSliceOverCudaThreadsConstStride::new(CudaExchangeBuffer::from_vec(
                buffer,
            )?),
        })
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }
}

#[cfg(not(target_os = "cuda"))]
impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool>
    ValueBuffer<T, M2D, true>
{
    pub fn iter(&self) -> impl Iterator<Item = Option<&T>> {
        self.mask
            .iter()
            .zip(self.buffer.iter())
            .map(|(mask, maybe)| {
                if *mask.read() {
                    Some(unsafe { maybe.read().assume_some_ref() })
                } else {
                    None
                }
            })
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = ValueRefMut<T, M2D>> {
        self.mask
            .iter_mut()
            .zip(self.buffer.iter_mut())
            .map(|(mask, value)| ValueRefMut { mask, value })
    }
}

#[cfg(target_os = "cuda")]
impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout> ValueBuffer<T, true, true> {
    pub fn with_value_for_core<F: FnOnce(Option<T>) -> Option<T>>(&mut self, inner: F) {
        let value = if self
            .mask
            .first()
            .map(CudaExchangeItem::read)
            .copied()
            .unwrap_or(false)
        {
            Some(unsafe { self.buffer.get_unchecked(0).read().assume_some_read() })
        } else {
            None
        };

        let result = inner(value);

        if let Some(mask) = self.mask.get_mut(0) {
            mask.write(result.is_some());

            if let Some(result) = result {
                unsafe { self.buffer.get_unchecked_mut(0) }.write(MaybeSome::Some(result));
            }
        }
    }
}

#[cfg(target_os = "cuda")]
impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2H: bool>
    ValueBuffer<T, true, M2H>
{
    pub fn take_value_for_core(&mut self) -> Option<T> {
        #[allow(clippy::option_if_let_else)]
        if let Some(mask) = self.mask.get_mut(0) {
            mask.write(false);

            if *mask.read() {
                Some(unsafe { self.buffer.get_unchecked(0).read().assume_some_read() })
            } else {
                None
            }
        } else {
            None
        }
    }
}

#[cfg(target_os = "cuda")]
impl<T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool>
    ValueBuffer<T, M2D, true>
{
    pub fn put_value_for_core(&mut self, value: Option<T>) {
        if let Some(mask) = self.mask.get_mut(0) {
            mask.write(value.is_some());

            if let Some(value) = value {
                unsafe { self.buffer.get_unchecked_mut(0) }.write(MaybeSome::Some(value));
            }
        }
    }
}

#[cfg(not(target_os = "cuda"))]
pub struct ValueRefMut<'v, T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool> {
    mask: &'v mut CudaExchangeItem<bool, true, true>,
    value: &'v mut CudaExchangeItem<MaybeSome<T>, M2D, true>,
}

#[cfg(not(target_os = "cuda"))]
impl<'v, T: StackOnly + PortableBitSemantics + TypeGraphLayout, const M2D: bool>
    ValueRefMut<'v, T, M2D>
{
    pub fn take(&mut self) -> Option<T> {
        if *self.mask.read() {
            self.mask.write(false);

            Some(unsafe { self.value.read().assume_some_read() })
        } else {
            None
        }
    }

    #[must_use]
    pub fn as_ref(&self) -> Option<&T> {
        if *self.mask.read() {
            Some(unsafe { self.value.read().assume_some_ref() })
        } else {
            None
        }
    }
}

#[cfg(not(target_os = "cuda"))]
impl<'v, T: StackOnly + PortableBitSemantics + TypeGraphLayout> ValueRefMut<'v, T, true> {
    #[must_use]
    pub fn as_mut(&mut self) -> Option<&mut T> {
        if *self.mask.read() {
            Some(unsafe { self.value.as_mut().assume_some_mut() })
        } else {
            None
        }
    }

    pub fn replace(&mut self, value: Option<T>) -> Option<T> {
        let old = if *self.mask.read() {
            Some(unsafe { self.value.read().assume_some_read() })
        } else {
            None
        };

        self.mask.write(value.is_some());

        if let Some(value) = value {
            self.value.write(MaybeSome::Some(value));
        }

        old
    }
}