rsfbclient_native/
xsqlda.rs

1use std::{
2    alloc,
3    ops::{Deref, DerefMut},
4    ptr,
5};
6
7use crate::ibase;
8
9pub struct XSqlDa {
10    ptr: ptr::NonNull<ibase::XSQLDA>,
11    len: i16,
12}
13
14unsafe impl Send for XSqlDa {}
15
16impl XSqlDa {
17    /// Allocates a new XSQLDA of length `len`
18    pub fn new(len: i16) -> Self {
19        #[allow(clippy::cast_ptr_alignment)]
20        let ptr = unsafe { alloc::alloc_zeroed(xsqlda_layout(len)) } as *mut ibase::XSQLDA;
21
22        let ptr = if let Some(ptr) = ptr::NonNull::new(ptr) {
23            ptr
24        } else {
25            alloc::handle_alloc_error(xsqlda_layout(len))
26        };
27
28        let mut xsqlda = Self { ptr, len };
29
30        xsqlda.version = ibase::SQLDA_VERSION1 as i16;
31        xsqlda.sqln = len;
32
33        xsqlda
34    }
35
36    /// Returns a mutable reference to a XSQLVAR
37    pub fn get_xsqlvar_mut(&mut self, col: usize) -> Option<&mut ibase::XSQLVAR> {
38        if col < self.len as usize {
39            let xsqlvar = unsafe {
40                let ptr = self.ptr.as_mut().sqlvar.as_mut_ptr();
41                std::slice::from_raw_parts_mut(ptr, self.len as usize)
42                    .get_unchecked_mut(col as usize)
43            };
44
45            Some(xsqlvar)
46        } else {
47            None
48        }
49    }
50}
51
52impl Deref for XSqlDa {
53    type Target = ibase::XSQLDA;
54
55    fn deref(&self) -> &Self::Target {
56        unsafe { self.ptr.as_ref() }
57    }
58}
59
60impl DerefMut for XSqlDa {
61    fn deref_mut(&mut self) -> &mut Self::Target {
62        unsafe { self.ptr.as_mut() }
63    }
64}
65
66impl Drop for XSqlDa {
67    fn drop(&mut self) {
68        unsafe { alloc::dealloc(self.ptr.as_ptr() as *mut u8, xsqlda_layout(self.len)) }
69    }
70}
71
72/// Calculates the memory layout (size and alignment) for a xsqlda
73fn xsqlda_layout(len: i16) -> alloc::Layout {
74    let (xsqlda_layout, _) = alloc::Layout::new::<ibase::XSQLDA>()
75        .extend(alloc::Layout::array::<ibase::XSQLVAR>((len - 1).max(0) as usize).unwrap())
76        .unwrap();
77
78    xsqlda_layout
79}