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
//! Private module that handles the implementation of the wrapper module

#![allow(dead_code)]

use std::cmp::min;
use std::os::raw::c_char;
use std::ptr;

/// Write a string message to a buffer. Accepts a const generic size `N` that
/// length of the message will check against (N must be the size of the buffer)
///
/// # Safety
///
/// `N` must be the buffer size. If it is inaccurate, memory safety cannot be
/// guaranteed.
///
/// This is public within the crate, since the parent model is not public
pub unsafe fn write_msg_to_buf<const N: usize>(msg: &[u8], buf: *mut c_char) {
    // message plus null terminator must fit in buffer
    let bytes_to_write = min(msg.len(), N - 1);

    unsafe {
        ptr::copy_nonoverlapping(msg.as_ptr().cast::<c_char>(), buf, bytes_to_write);
        *buf.add(bytes_to_write) = 0;
    }
}

#[cfg(test)]
mod tests {
    use std::ffi::{c_ulong, c_void, CStr};

    use udf_sys::{Item_result, UDF_ARGS};

    use super::*;
    use crate::prelude::*;

    const MSG: &str = "message";
    const BUF_SIZE: usize = MSG.len() + 1;

    #[test]
    fn write_msg_ok() {
        let mut mbuf = [1 as c_char; BUF_SIZE];

        unsafe {
            write_msg_to_buf::<BUF_SIZE>(MSG.as_bytes(), mbuf.as_mut_ptr());
            let s = CStr::from_ptr(mbuf.as_ptr()).to_str().unwrap();

            assert_eq!(s, MSG);
        }
    }

    #[test]
    fn write_message_too_long() {
        const NEW_BUF_SIZE: usize = BUF_SIZE - 1;

        let mut mbuf = [1 as c_char; NEW_BUF_SIZE];
        unsafe {
            write_msg_to_buf::<NEW_BUF_SIZE>(MSG.as_bytes(), mbuf.as_mut_ptr());
            let s = CStr::from_ptr(mbuf.as_ptr()).to_str().unwrap();
            assert_eq!(*s, MSG[..MSG.len() - 1]);
        };
    }

    #[test]
    fn argtype_from_ptr_null() {
        // Just test null pointers here
        unsafe {
            assert_eq!(
                SqlResult::from_ptr(ptr::null(), Item_result::INT_RESULT, 0),
                Ok(SqlResult::Int(None))
            );
            assert_eq!(
                SqlResult::from_ptr(ptr::null(), Item_result::REAL_RESULT, 0),
                Ok(SqlResult::Real(None))
            );
            assert_eq!(
                SqlResult::from_ptr(ptr::null(), Item_result::STRING_RESULT, 0),
                Ok(SqlResult::String(None))
            );
            assert_eq!(
                SqlResult::from_ptr(ptr::null(), Item_result::DECIMAL_RESULT, 0),
                Ok(SqlResult::Decimal(None))
            );
            assert!(SqlResult::from_ptr(ptr::null(), Item_result::INVALID_RESULT, 0).is_err());
        }
    }

    #[test]
    fn argtype_from_ptr_notnull() {
        // Just test null pointers here
        unsafe {
            let ival = -1000i64;
            assert_eq!(
                SqlResult::from_ptr(&ival as *const i64 as *const u8, Item_result::INT_RESULT, 0),
                Ok(SqlResult::Int(Some(ival)))
            );

            let rval = -1000.0f64;
            assert_eq!(
                SqlResult::from_ptr(
                    &rval as *const f64 as *const u8,
                    Item_result::REAL_RESULT,
                    0
                ),
                Ok(SqlResult::Real(Some(rval)))
            );

            let sval = "this is a string";
            assert_eq!(
                SqlResult::from_ptr(sval.as_ptr(), Item_result::STRING_RESULT, sval.len()),
                Ok(SqlResult::String(Some(sval.as_bytes())))
            );

            let dval = "123.456";
            assert_eq!(
                SqlResult::from_ptr(dval.as_ptr(), Item_result::DECIMAL_RESULT, dval.len()),
                Ok(SqlResult::Decimal(Some(dval)))
            );

            assert!(
                SqlResult::from_ptr(dval.as_ptr(), Item_result::INVALID_RESULT, dval.len())
                    .is_err()
            );
        }
    }

    const ARG_COUNT: usize = 4;

    const IVAL: i64 = -1000i64;
    const RVAL: f64 = -1234.5678f64;
    const SVAL: &str = "this is a string";
    const DVAL: &str = "123.456";

    #[test]
    fn process_args_ok() {
        let mut arg_types = [
            Item_result::INT_RESULT,
            Item_result::REAL_RESULT,
            Item_result::STRING_RESULT,
            Item_result::DECIMAL_RESULT,
        ];

        let mut arg_ptrs: [*const u8; ARG_COUNT] = [
            &IVAL as *const i64 as *const u8,
            &RVAL as *const f64 as *const u8,
            SVAL.as_ptr(),
            DVAL.as_ptr(),
        ];

        let mut arg_lens = [0u64, 0, SVAL.len() as u64, DVAL.len() as u64];
        let mut maybe_null = [true, true, false, false];
        let attrs = ["ival", "rval", "sval", "dval"];
        let mut attr_ptrs = [
            attrs[0].as_ptr(),
            attrs[1].as_ptr(),
            attrs[2].as_ptr(),
            attrs[3].as_ptr(),
        ];
        let mut attr_lens = [
            attrs[0].len(),
            attrs[1].len(),
            attrs[2].len(),
            attrs[3].len(),
        ];

        let udf_args = UDF_ARGS {
            arg_count: ARG_COUNT as u32,
            arg_type: arg_types.as_mut_ptr(),
            args: arg_ptrs.as_mut_ptr() as *const *const c_char,
            lengths: arg_lens.as_mut_ptr(),
            maybe_null: maybe_null.as_mut_ptr() as *mut c_char,
            attributes: attr_ptrs.as_mut_ptr() as *const *const c_char,
            attribute_lengths: attr_lens.as_mut_ptr() as *mut c_ulong,
            extension: ptr::null_mut::<c_void>(),
        };

        let arglist: &ArgList<Init> = unsafe { ArgList::from_arg_ptr(&udf_args) };
        let res: Vec<_> = arglist.into_iter().collect();

        let expected_args = [
            SqlResult::Int(Some(IVAL)),
            SqlResult::Real(Some(RVAL)),
            SqlResult::String(Some(SVAL.as_bytes())),
            SqlResult::Decimal(Some(DVAL)),
        ];

        for i in 0..ARG_COUNT {
            assert_eq!(res[i].value, expected_args[i]);
            assert_eq!(res[i].maybe_null, maybe_null[i]);
            assert_eq!(res[i].attribute, attrs[i]);
            // assert_eq!(unsafe { *res[i].type_ptr }, arg_types[i]);
        }
    }
}