odbc_api/
fixed_sized.rs

1use crate::{
2    buffers::{FetchRowMember, Indicator},
3    handles::{CData, CDataMut, DataType, HasDataType},
4    parameter::{CElement, OutputParameter},
5};
6use odbc_sys::{CDataType, Date, Numeric, Time, Timestamp};
7use std::{
8    ffi::c_void,
9    ptr::{null, null_mut},
10};
11
12/// New type wrapping u8 and binding as SQL_BIT.
13///
14/// If rust would guarantee the representation of `bool` to be an `u8`, `bool` would be the obvious
15/// choice instead. Alas it is not and someday on some platform `bool` might be something else than
16/// a `u8` so let's use this new type instead.
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Ord, PartialOrd)]
18pub struct Bit(pub u8);
19
20impl Bit {
21    /// Maps `true` to `1` and `false` to `0`.
22    ///
23    /// ```
24    /// use odbc_api::Bit;
25    ///
26    /// assert_eq!(Bit(0), Bit::from_bool(false));
27    /// assert_eq!(Bit(1), Bit::from_bool(true));
28    /// ```
29    pub fn from_bool(boolean: bool) -> Self {
30        if boolean {
31            Bit(1)
32        } else {
33            Bit(0)
34        }
35    }
36
37    /// Maps `1` to `true`, `0` to `false`. Panics if `Bit` should be invalid (not `0` or `1`).
38    pub fn as_bool(self) -> bool {
39        match self.0 {
40            0 => false,
41            1 => true,
42            _ => panic!("Invalid boolean representation in Bit."),
43        }
44    }
45}
46
47/// A plain old data type. With an associated C Type. Must be completely stack allocated without any
48/// external references. In addition to that the buffer size must be known to ODBC in advance.
49///
50/// # Safety
51///
52/// A type implementing this trait, must be a fixed sized type. The information in the `C_DATA_TYPE`
53/// constant must be enough to determine both the size and the buffer length of an Instance.
54pub unsafe trait Pod: Default + Copy + CElement + CDataMut + 'static {
55    /// ODBC C Data type used to bind instances to a statement.
56    const C_DATA_TYPE: CDataType;
57}
58
59macro_rules! impl_pod {
60    ($t:ident, $c_data_type:expr) => {
61        unsafe impl CData for $t {
62            fn cdata_type(&self) -> CDataType {
63                $c_data_type
64            }
65
66            fn indicator_ptr(&self) -> *const isize {
67                // Fixed sized types do not require a length indicator.
68                null()
69            }
70
71            fn value_ptr(&self) -> *const c_void {
72                self as *const $t as *const c_void
73            }
74
75            fn buffer_length(&self) -> isize {
76                0
77            }
78        }
79
80        unsafe impl CDataMut for $t {
81            /// Indicates the length of variable sized types. May be zero for fixed sized types.
82            fn mut_indicator_ptr(&mut self) -> *mut isize {
83                null_mut()
84            }
85
86            /// Pointer to a value corresponding to the one described by `cdata_type`.
87            fn mut_value_ptr(&mut self) -> *mut c_void {
88                self as *mut $t as *mut c_void
89            }
90        }
91
92        unsafe impl CElement for $t {
93            /// Fixed sized types are always complete
94            fn assert_completness(&self) {}
95        }
96
97        unsafe impl Pod for $t {
98            const C_DATA_TYPE: CDataType = $c_data_type;
99        }
100
101        unsafe impl FetchRowMember for $t {
102            fn indicator(&self) -> Option<Indicator> {
103                None
104            }
105        }
106    };
107}
108
109impl_pod!(f64, CDataType::Double);
110impl_pod!(f32, CDataType::Float);
111impl_pod!(Date, CDataType::TypeDate);
112impl_pod!(Timestamp, CDataType::TypeTimestamp);
113impl_pod!(Time, CDataType::TypeTime);
114impl_pod!(Numeric, CDataType::Numeric);
115impl_pod!(i16, CDataType::SShort);
116impl_pod!(u16, CDataType::UShort);
117impl_pod!(i32, CDataType::SLong);
118impl_pod!(u32, CDataType::ULong);
119impl_pod!(i8, CDataType::STinyInt);
120impl_pod!(u8, CDataType::UTinyInt);
121impl_pod!(Bit, CDataType::Bit);
122impl_pod!(i64, CDataType::SBigInt);
123impl_pod!(u64, CDataType::UBigInt);
124
125// While the C-Type is independent of the Data (SQL) Type in the source, there are often DataTypes
126// which are a natural match for the C-Type in question. These can be used to spare the user to
127// specify that an i32 is supposed to be bound as an SQL Integer.
128
129macro_rules! impl_input_fixed_sized {
130    ($t:ident, $data_type:expr) => {
131        impl HasDataType for $t {
132            fn data_type(&self) -> DataType {
133                $data_type
134            }
135        }
136
137        unsafe impl OutputParameter for $t {}
138    };
139}
140
141impl_input_fixed_sized!(f64, DataType::Double);
142impl_input_fixed_sized!(f32, DataType::Real);
143impl_input_fixed_sized!(Date, DataType::Date);
144impl_input_fixed_sized!(i16, DataType::SmallInt);
145impl_input_fixed_sized!(i32, DataType::Integer);
146impl_input_fixed_sized!(i8, DataType::TinyInt);
147impl_input_fixed_sized!(Bit, DataType::Bit);
148impl_input_fixed_sized!(i64, DataType::BigInt);
149
150// Support for fixed size types, which are not unsigned. Time, Date and timestamp types could be
151// supported, implementation DataType would need to take an instance into account.
152
153#[cfg(test)]
154mod tests {
155
156    use super::Bit;
157
158    /// `as_bool` should panic if bit is neither 0 or 1.
159    #[test]
160    #[should_panic(expected = "Invalid boolean representation in Bit.")]
161    fn invalid_bit() {
162        let bit = Bit(2);
163        bit.as_bool();
164    }
165}