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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use crate::{
    fixed_sized::{Bit, Pod},
    handles::{CData, CDataMut},
};
use odbc_sys::{Date, Time, Timestamp, NULL_DATA};
use std::{
    ffi::c_void,
    mem::size_of,
    ptr::{null, null_mut},
};

pub type OptF64Column = ColumnWithIndicator<f64>;
pub type OptF32Column = ColumnWithIndicator<f32>;
pub type OptDateColumn = ColumnWithIndicator<Date>;
pub type OptTimestampColumn = ColumnWithIndicator<Timestamp>;
pub type OptTimeColumn = ColumnWithIndicator<Time>;
pub type OptI8Column = ColumnWithIndicator<i8>;
pub type OptI16Column = ColumnWithIndicator<i16>;
pub type OptI32Column = ColumnWithIndicator<i32>;
pub type OptI64Column = ColumnWithIndicator<i64>;
pub type OptU8Column = ColumnWithIndicator<u8>;
pub type OptBitColumn = ColumnWithIndicator<Bit>;

/// Column buffer for fixed sized type, also binding an indicator buffer to handle NULL.
#[derive(Debug)]
pub struct ColumnWithIndicator<T> {
    values: Vec<T>,
    indicators: Vec<isize>,
}

impl<T> ColumnWithIndicator<T>
where
    T: Default + Clone,
{
    pub fn new(batch_size: usize) -> Self {
        Self {
            values: vec![T::default(); batch_size],
            indicators: vec![NULL_DATA; batch_size],
        }
    }

    /// Access the value at a specific row index.
    ///
    /// The buffer size is not automatically adjusted to the size of the last row set. It is the
    /// callers responsibility to ensure, a value has been written to the indexed position by
    /// [`crate::Cursor::fetch`] using the value bound to the cursor with
    /// [`crate::Cursor::set_num_result_rows_fetched`].
    pub fn iter(&self, num_rows: usize) -> NullableSlice<'_, T> {
        NullableSlice {
            indicators: &self.indicators[0..num_rows],
            values: &self.values[0..num_rows],
        }
    }

    /// Fills the column with NULL, between From and To
    pub fn fill_null(&mut self, from: usize, to: usize) {
        for index in from..to {
            self.indicators[index] = NULL_DATA;
        }
    }

    /// Create a writer which writes to the first `n` elements of the buffer.
    pub fn writer_n(&mut self, n: usize) -> NullableSliceMut<'_, T> {
        NullableSliceMut {
            indicators: &mut self.indicators[0..n],
            values: &mut self.values[0..n],
        }
    }

    /// Maximum number elements which the column may hold.
    pub fn capacity(&self) -> usize {
        self.indicators.len()
    }
}

/// Iterates over the elements of a column buffer. Returned by
/// [`crate::buffers::ColumnarBuffer::column`] as part of an [`crate::buffers::AnyColumnView`].
#[derive(Debug, Clone, Copy)]
pub struct NullableSlice<'a, T> {
    indicators: &'a [isize],
    values: &'a [T],
}

impl<'a, T> NullableSlice<'a, T> {
    /// `true` if the slice has a length of `0`.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Number of entries in this slice of the buffer
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Read access to the underlying raw value and indicator buffer.
    ///
    /// The number of elements in the buffer is equal to the number of rows returned in the current
    /// result set. Yet the content of any value, those associated value in the indicator buffer is
    /// [`crate::sys::NULL_DATA`] is undefined.
    ///
    /// This method is useful for writing performant bindings to datastructures with similar binary
    /// layout, as it allows for using memcopy rather than iterating over individual values.
    ///
    /// # Example
    ///
    /// ```
    /// use odbc_api::{buffers::NullableSlice, sys::NULL_DATA};
    ///
    /// // Memcopy the values out of the buffer, and make a mask of bools indicating the NULL
    /// // values.
    /// fn copy_values_and_make_mask(odbc_slice: NullableSlice<i32>) -> (Vec<i32>, Vec<bool>) {
    ///     let (values, indicators) = odbc_slice.raw_values();
    ///     let values = values.to_vec();
    ///     // Create array of bools indicating null values.
    ///     let mask: Vec<bool> = indicators
    ///         .iter()
    ///         .map(|&indicator| indicator != NULL_DATA)
    ///         .collect();
    ///     (values, mask)
    /// }
    /// ```
    pub fn raw_values(&self) -> (&'a [T], &'a [isize]) {
        (self.values, self.indicators)
    }
}

impl<'a, T> Iterator for NullableSlice<'a, T> {
    type Item = Option<&'a T>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(&ind) = self.indicators.first() {
            let item = if ind == NULL_DATA {
                None
            } else {
                Some(&self.values[0])
            };
            self.indicators = &self.indicators[1..];
            self.values = &self.values[1..];
            Some(item)
        } else {
            None
        }
    }
}

unsafe impl<T> CData for ColumnWithIndicator<T>
where
    T: Pod,
{
    fn cdata_type(&self) -> odbc_sys::CDataType {
        T::C_DATA_TYPE
    }

    fn indicator_ptr(&self) -> *const isize {
        self.indicators.as_ptr() as *const isize
    }

    fn value_ptr(&self) -> *const c_void {
        self.values.as_ptr() as *const c_void
    }

    fn buffer_length(&self) -> isize {
        size_of::<T>().try_into().unwrap()
    }
}

unsafe impl<T> CDataMut for ColumnWithIndicator<T>
where
    T: Pod,
{
    fn mut_indicator_ptr(&mut self) -> *mut isize {
        self.indicators.as_mut_ptr() as *mut isize
    }

    fn mut_value_ptr(&mut self) -> *mut c_void {
        self.values.as_mut_ptr() as *mut c_void
    }
}

unsafe impl<T> CData for Vec<T>
where
    T: Pod,
{
    fn cdata_type(&self) -> odbc_sys::CDataType {
        T::C_DATA_TYPE
    }

    fn indicator_ptr(&self) -> *const isize {
        null()
    }

    fn value_ptr(&self) -> *const c_void {
        self.as_ptr() as *const c_void
    }

    fn buffer_length(&self) -> isize {
        size_of::<T>().try_into().unwrap()
    }
}

unsafe impl<T> CDataMut for Vec<T>
where
    T: Pod,
{
    fn mut_indicator_ptr(&mut self) -> *mut isize {
        null_mut()
    }

    fn mut_value_ptr(&mut self) -> *mut c_void {
        self.as_mut_ptr() as *mut c_void
    }
}

/// Used to fill a column buffer with an iterator. Returned by [`super::ColumnarBuffer::column_mut`]
/// as part of an [`crate::buffers::AnyColumnViewMut`].
#[derive(Debug)]
pub struct NullableSliceMut<'a, T> {
    indicators: &'a mut [isize],
    values: &'a mut [T],
}

impl<'a, T> NullableSliceMut<'a, T> {
    /// `true` if the slice has a length of `0`.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Number of entries in this slice of the buffer
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Write access to the underlying raw value and indicator buffer.
    ///
    /// The number of elements in the buffer is equal to `len`.
    ///
    /// This method is useful for writing performant bindings to datastructures with similar binary
    /// layout, as it allows for using memcopy rather than iterating over individual values.
    ///
    /// # Example
    ///
    /// ```
    /// use odbc_api::{buffers::NullableSliceMut, sys::NULL_DATA};
    ///
    /// // Memcopy the values into the buffer, and set indicators according to mask
    /// // values.
    /// fn copy_values_and_make_mask(
    ///     new_values: &[i32],
    ///     mask: &[bool],
    ///     odbc_slice: &mut NullableSliceMut<i32>)
    /// {
    ///     let (values, indicators) = odbc_slice.raw_values();
    ///     values.copy_from_slice(new_values);
    ///     // Create array of bools indicating null values.
    ///     indicators.iter_mut().zip(mask.iter()).for_each(|(indicator, &mask)| {
    ///         *indicator = if mask {
    ///             0
    ///         } else {
    ///             NULL_DATA
    ///         }
    ///     });
    /// }
    /// ```
    pub fn raw_values(&mut self) -> (&mut [T], &mut [isize]) {
        (self.values, self.indicators)
    }
}

impl<'a, T> NullableSliceMut<'a, T> {
    /// Writes the elements returned by the iterator into the buffer, starting at the beginning.
    /// Writes elements until the iterator returns `None` or the buffer can not hold more elements.
    pub fn write(&mut self, it: impl Iterator<Item = Option<T>>) {
        for (index, item) in it.enumerate().take(self.values.len()) {
            if let Some(value) = item {
                self.indicators[index] = 0;
                self.values[index] = value;
            } else {
                self.indicators[index] = NULL_DATA;
            }
        }
    }
}