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
use sys::*;
use std::ffi::CStr;
use std::ptr::null;

/// A type implementing this trait can be passed as a string argument in API calls
pub unsafe trait SqlStr {
    /// Returns a pointer to the start of the string
    fn as_text_ptr(&self) -> *const SQLCHAR;
    /// Returns buffer length or SQL_NTS
    fn text_length(&self) -> SQLSMALLINT;
    /// Returns buffer length or SQL_NTSL
    fn text_length_int(&self) -> SQLINTEGER;
}

unsafe impl SqlStr for CStr {
    fn as_text_ptr(&self) -> *const SQLCHAR {
        self.as_ptr() as *const SQLCHAR
    }

    fn text_length(&self) -> SQLSMALLINT {
        SQL_NTS
    }

    fn text_length_int(&self) -> SQLINTEGER {
        SQL_NTSL
    }
}

/// For passing a buffer without terminating NULL
unsafe impl SqlStr for [u8] {
    fn as_text_ptr(&self) -> *const SQLCHAR {
        if self.is_empty() {
            null()
        } else {
            self.as_ptr()
        }
    }

    fn text_length(&self) -> SQLSMALLINT {
        if self.len() > SQLSMALLINT::max_value() as usize {
            panic!(
                "Buffer length of {} is greater than SQLSMALLINT::MAX: {}",
                self.len(),
                SQLSMALLINT::max_value()
            );
        }
        self.len() as SQLSMALLINT
    }

    fn text_length_int(&self) -> SQLINTEGER {
        if self.len() > SQLINTEGER::max_value() as usize {
            panic!(
                "Buffer length of {} is greater than SQLINTEGER::MAX: {}",
                self.len(),
                SQLINTEGER::max_value()
            );
        }
        self.len() as SQLINTEGER
    }
}

/// For passing a buffer without terminating NULL
unsafe impl SqlStr for str {
    fn as_text_ptr(&self) -> *const SQLCHAR {
        if self.is_empty() {
            null()
        } else {
            self.as_ptr()
        }
    }

    fn text_length(&self) -> SQLSMALLINT {
        if self.len() > SQLSMALLINT::max_value() as usize {
            panic!(
                "Buffer length of {} is greater than SQLSMALLINT::MAX: {}",
                self.len(),
                SQLSMALLINT::max_value()
            );
        }
        // str::len is in bytes, so this should work
        self.len() as SQLSMALLINT
    }

    fn text_length_int(&self) -> SQLINTEGER {
        if self.len() > SQLINTEGER::max_value() as usize {
            panic!(
                "Buffer length of {} is greater than SQLINTEGER::MAX: {}",
                self.len(),
                SQLINTEGER::max_value()
            );
        }

        self.len() as SQLINTEGER
    }
}