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
use std::{
    ffi::{CStr, CString},
    os::raw::c_char,
};

use widestring::{U16CStr, U16CString, U16String};

use super::traits::{FFIFromRust, FFIToRust};

/// An array of 8-bit characters terminated by a null character.
#[repr(C)]
#[derive(Debug)]
pub struct FFIString {
    data: *mut c_char,
    size: usize,
    capacity: usize,
}

impl FFIString {
    /// Returns the length of the string (excluding the null byte)
    pub const fn len(&self) -> usize {
        self.size
    }

    /// Returns `true` if the string has a length of 0.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub unsafe fn to_str(&self) -> Result<&str, std::str::Utf8Error> {
        if self.is_empty() {
            Ok("")
        } else {
            CStr::from_ptr(self.data).to_str()
        }
    }
}

impl FFIToRust for FFIString {
    type Target = String;

    unsafe fn to_rust(&self) -> Self::Target {
        self.to_str().expect("CStr::to_str failed").to_string()
    }
}

#[repr(C)]
#[derive(Debug)]
pub struct OwnedFFIString {
    data: *mut c_char,
    size: usize,
    capacity: usize,
}

impl OwnedFFIString {
    /// Returns the length of the string (excluding the null byte)
    pub const fn len(&self) -> usize {
        self.size
    }

    /// Returns `true` if the string has a length of 0.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl FFIFromRust for OwnedFFIString {
    type From = String;

    unsafe fn from_rust(string: &Self::From) -> Self {
        let cstring = CString::new(string.clone()).expect("CString::new failed");
        let len = cstring.as_bytes().len();
        Self {
            data: cstring.into_raw(),
            size: len,
            capacity: len + 1,
        }
    }
}

impl Drop for OwnedFFIString {
    fn drop(&mut self) {
        unsafe {
            std::mem::drop(CString::from_raw(self.data));
        }
    }
}

/// An array of 16-bit characters terminated by a null character.
#[repr(C)]
#[derive(Debug)]
pub struct FFIWString {
    data: *mut u16,
    size: usize,
    capacity: usize,
}

impl FFIWString {
    /// Returns the length of the string (excluding the null byte)
    pub const fn len(&self) -> usize {
        self.size
    }

    /// Returns `true` if the sequence has a length of 0.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl FFIToRust for FFIWString {
    type Target = U16String;

    unsafe fn to_rust(&self) -> Self::Target {
        if self.is_empty() {
            Self::Target::new()
        } else {
            U16CStr::from_ptr_str(self.data).to_ustring()
        }
    }
}

#[repr(C)]
#[derive(Debug)]
pub struct OwnedFFIWString {
    data: *mut u16,
    size: usize,
    capacity: usize,
}

impl OwnedFFIWString {
    /// Returns the length of the string (excluding the null byte)
    pub const fn len(&self) -> usize {
        self.size
    }

    /// Returns `true` if the sequence has a length of 0.
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl FFIFromRust for OwnedFFIWString {
    type From = U16String;

    unsafe fn from_rust(string: &Self::From) -> Self {
        let cstring = U16CString::new(string.clone()).expect("U16CString::new failed");
        let len = cstring.len();
        Self {
            data: cstring.into_raw(),
            size: len,
            capacity: len + 1,
        }
    }
}

impl Drop for OwnedFFIWString {
    fn drop(&mut self) {
        unsafe {
            std::mem::drop(U16CString::from_raw(self.data));
        }
    }
}

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

    #[test]
    fn owned_ffi_string_new() {
        let string = "abcde".into();
        let cstring = unsafe { OwnedFFIString::from_rust(&string) };
        let native_string = FFIString {
            data: cstring.data,
            size: cstring.size,
            capacity: cstring.capacity,
        };

        assert_eq!(string, unsafe { native_string.to_rust() });
    }

    #[test]
    fn owned_ffi_wstring_new() {
        let wstring = U16String::from_str("あいうえお");
        let cwstring = unsafe { OwnedFFIWString::from_rust(&wstring) };
        let native_wstring = FFIWString {
            data: cwstring.data,
            size: cwstring.size,
            capacity: cwstring.capacity,
        };

        assert_eq!(wstring, unsafe { native_wstring.to_rust() });
    }
}