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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
//! Functions related to strictly the `process` UDF components

#![allow(clippy::module_name_repetitions)]
#![allow(clippy::option_if_let_else)]

#[cfg(feature = "logging-debug")]
use std::any::type_name;
use std::ffi::{c_char, c_uchar, c_ulong};
use std::num::NonZeroU8;
use std::ptr;

use udf_sys::{UDF_ARGS, UDF_INIT};

use super::helpers::{buf_result_callback, BufOptions};
#[cfg(feature = "logging-debug")]
use crate::udf_log;
use crate::{ArgList, BasicUdf, ProcessError, UdfCfg};

/// Callback for properly unwrapping and setting values for `Option<T>`
///
/// Returns `None` if the value is `Err` or `None`, `Some` otherwise
#[inline]
unsafe fn ret_callback_option<R>(
    res: Result<Option<R>, ProcessError>,
    error: *mut c_uchar,
    is_null: *mut c_uchar,
) -> Option<R> {
    let transposed = res.transpose();

    // Perform action for if internal is `None`
    let Some(res_some) = transposed else {
        // We have a None result
        *is_null = 1;
        return None;
    };

    // Rest of the behavior is in `ret_callback`
    ret_callback(res_some, error, is_null)
}

/// Callback for properly unwrapping and setting values for any `T`
///
/// Returns `None` if the value is `Err`, `Some` otherwise
#[inline]
unsafe fn ret_callback<R>(
    res: Result<R, ProcessError>,
    error: *mut c_uchar,
    is_null: *mut c_uchar,
) -> Option<R> {
    // Error case: set an error, and set length to 0 if applicable
    let Ok(val) = res else {
        *error = 1;
        return None;
    };

    // Ok case: just return the desired value
    *is_null = c_uchar::from(false);

    Some(val)
}

/// Apply the `process` function for any implementation returning a nonbuffer type
/// (`f64`, `i64`)
#[inline]
pub unsafe fn wrap_process_basic<U, R>(
    initid: *mut UDF_INIT,
    args: *mut UDF_ARGS,
    is_null: *mut c_uchar,
    error: *mut c_uchar,
) -> R
where
    for<'a> U: BasicUdf<Returns<'a> = R>,
    R: Default,
{
    #[cfg(feature = "logging-debug")]
    udf_log!(Debug: "calling process for `{}`", type_name::<U>());

    let cfg = UdfCfg::from_raw_ptr(initid);
    let arglist = ArgList::from_raw_ptr(args);
    let mut b = cfg.retrieve_box();
    let err = *(error as *const Option<NonZeroU8>);
    let proc_res = U::process(&mut b, cfg, arglist, err);
    cfg.store_box(b);

    ret_callback(proc_res, error, is_null).unwrap_or_default()
}

/// Apply the `process` function for any implementation returning an optional
/// nonbuffer type (`Option<f64>`, `Option<i64>`)
#[inline]
pub unsafe fn wrap_process_basic_option<U, R>(
    initid: *mut UDF_INIT,
    args: *mut UDF_ARGS,
    is_null: *mut c_uchar,
    error: *mut c_uchar,
) -> R
where
    for<'a> U: BasicUdf<Returns<'a> = Option<R>>,
    R: Default,
{
    #[cfg(feature = "logging-debug")]
    udf_log!(Debug: "calling process for `{}`", type_name::<U>());

    let cfg = UdfCfg::from_raw_ptr(initid);
    let arglist = ArgList::from_raw_ptr(args);
    let mut b = cfg.retrieve_box();
    let err = *(error as *const Option<NonZeroU8>);
    let proc_res = U::process(&mut b, cfg, arglist, err);
    cfg.store_box(b);

    ret_callback_option(proc_res, error, is_null).unwrap_or_default()
}

/// Apply the `process` function for any implementation returning a buffer type
/// (`String`, `Vec<u8>`, `str`, `[u8]`)
#[inline]
pub unsafe fn wrap_process_buf<U>(
    initid: *mut UDF_INIT,
    args: *mut UDF_ARGS,
    result: *mut c_char,
    length: *mut c_ulong,
    is_null: *mut c_uchar,
    error: *mut c_uchar,
    can_return_ref: bool,
) -> *const c_char
where
    for<'b> U: BasicUdf,
    for<'a> <U as BasicUdf>::Returns<'a>: AsRef<[u8]>,
{
    #[cfg(feature = "logging-debug")]
    udf_log!(Debug: "calling process for `{}`", type_name::<U>());

    let cfg = UdfCfg::from_raw_ptr(initid);
    let arglist = ArgList::from_raw_ptr(args);
    let mut b = cfg.retrieve_box();
    let err = *(error as *const Option<NonZeroU8>);
    let proc_res = U::process(&mut b, cfg, arglist, err);
    let buf_opts = BufOptions::new(result, length, can_return_ref);

    let post_effects_val = ret_callback(proc_res, error, is_null);

    let ret = match post_effects_val {
        Some(ref v) => buf_result_callback::<U, _>(v, &buf_opts).unwrap_or_else(|| {
            *error = 1;
            ptr::null()
        }),
        None => ptr::null(),
    };

    std::mem::forget(post_effects_val);
    cfg.store_box(b);

    ret
}

/// Apply the `process` function for any implementation returning a buffer type
/// (`Option<String>`, `Option<Vec<u8>>`, `Option<str>`, `Option<[u8]>`)
#[inline]
pub unsafe fn wrap_process_buf_option<U, B>(
    initid: *mut UDF_INIT,
    args: *mut UDF_ARGS,
    result: *mut c_char,
    length: *mut c_ulong,
    is_null: *mut c_uchar,
    error: *mut c_uchar,
    can_return_ref: bool,
) -> *const c_char
where
    for<'a> U: BasicUdf<Returns<'a> = Option<B>>,
    B: AsRef<[u8]>,
{
    #[cfg(feature = "logging-debug")]
    udf_log!(Debug: "calling process for `{}`", type_name::<U>());

    let cfg = UdfCfg::from_raw_ptr(initid);
    let arglist = ArgList::from_raw_ptr(args);
    let err = *(error as *const Option<NonZeroU8>);
    let mut b = cfg.retrieve_box();
    let proc_res = U::process(&mut b, cfg, arglist, err);
    let buf_opts = BufOptions::new(result, length, can_return_ref);

    let post_effects_val = ret_callback_option(proc_res, error, is_null);

    let ret = match post_effects_val {
        Some(ref v) => {
            if let Some(x) = buf_result_callback::<U, _>(v, &buf_opts) {
                x
            } else {
                *error = 1;
                ptr::null()
            }
        }
        None => ptr::null(),
    };

    std::mem::forget(post_effects_val);
    cfg.store_box(b);

    ret
}

#[cfg(test)]
mod tests {
    use super::*;

    struct ExampleInt;
    struct ExampleIntOpt;
    struct ExampleBuf;
    struct ExampleBufOpt;

    impl BasicUdf for ExampleInt {
        type Returns<'a> = i64;

        fn init(_cfg: &UdfCfg<crate::Init>, _args: &ArgList<crate::Init>) -> Result<Self, String> {
            todo!()
        }

        fn process<'a>(
            &'a mut self,
            _cfg: &UdfCfg<crate::Process>,
            _args: &ArgList<crate::Process>,
            _error: Option<NonZeroU8>,
        ) -> Result<Self::Returns<'a>, ProcessError> {
            todo!()
        }
    }
    impl BasicUdf for ExampleIntOpt {
        type Returns<'a> = Option<i64>;

        fn init(_cfg: &UdfCfg<crate::Init>, _args: &ArgList<crate::Init>) -> Result<Self, String> {
            todo!()
        }

        fn process<'a>(
            &'a mut self,
            _cfg: &UdfCfg<crate::Process>,
            _args: &ArgList<crate::Process>,
            _error: Option<NonZeroU8>,
        ) -> Result<Self::Returns<'a>, ProcessError> {
            todo!()
        }
    }

    impl BasicUdf for ExampleBuf {
        type Returns<'a> = &'a str;

        fn init(_cfg: &UdfCfg<crate::Init>, _args: &ArgList<crate::Init>) -> Result<Self, String> {
            todo!()
        }

        fn process<'a>(
            &'a mut self,
            _cfg: &UdfCfg<crate::Process>,
            _args: &ArgList<crate::Process>,
            _error: Option<NonZeroU8>,
        ) -> Result<Self::Returns<'a>, ProcessError> {
            todo!()
        }
    }
    impl BasicUdf for ExampleBufOpt {
        type Returns<'a> = Option<Vec<u8>>;

        fn init(_cfg: &UdfCfg<crate::Init>, _args: &ArgList<crate::Init>) -> Result<Self, String> {
            todo!()
        }

        fn process<'a>(
            &'a mut self,
            _cfg: &UdfCfg<crate::Process>,
            _args: &ArgList<crate::Process>,
            _error: Option<NonZeroU8>,
        ) -> Result<Self::Returns<'a>, ProcessError> {
            todo!()
        }
    }

    #[test]
    #[should_panic]
    #[allow(unreachable_code)]
    #[allow(clippy::diverging_sub_expression)]
    fn test_fn_sig() {
        // Just validate our function signatures with compile tests

        unsafe {
            wrap_process_basic::<ExampleInt, _>(todo!(), todo!(), todo!(), todo!());
            wrap_process_basic_option::<ExampleIntOpt, _>(todo!(), todo!(), todo!(), todo!());
            wrap_process_buf::<ExampleBuf>(
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
            );
            wrap_process_buf_option::<ExampleBufOpt, _>(
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
                todo!(),
            );
        }
    }
}