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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use crate::Error;
use libc::{self, c_char, c_void};
use std::ffi::{CStr, CString};
use std::path::Path;
use std::ptr;
pub(crate) unsafe fn from_cstr(ptr: *const c_char) -> String {
let cstr = CStr::from_ptr(ptr as *const _);
String::from_utf8_lossy(cstr.to_bytes()).into_owned()
}
pub(crate) unsafe fn raw_data(ptr: *const c_char, size: usize) -> Option<Vec<u8>> {
if ptr.is_null() {
None
} else {
let mut dst = vec![0; size];
ptr::copy_nonoverlapping(ptr as *const u8, dst.as_mut_ptr(), size);
Some(dst)
}
}
pub fn error_message(ptr: *const c_char) -> String {
unsafe {
let s = from_cstr(ptr);
libc::free(ptr as *mut c_void);
s
}
}
pub fn opt_bytes_to_ptr<T: AsRef<[u8]>>(opt: Option<T>) -> *const c_char {
match opt {
Some(v) => v.as_ref().as_ptr() as *const c_char,
None => ptr::null(),
}
}
pub(crate) fn to_cpath<P: AsRef<Path>>(path: P) -> Result<CString, Error> {
match CString::new(path.as_ref().to_string_lossy().as_bytes()) {
Ok(c) => Ok(c),
Err(e) => Err(Error::new(format!(
"Failed to convert path to CString: {}",
e,
))),
}
}
macro_rules! ffi_try {
( $($function:ident)::*() ) => {
ffi_try_impl!($($function)::*())
};
( $($function:ident)::*( $arg1:expr $(, $arg:expr)* $(,)? ) ) => {
ffi_try_impl!($($function)::*($arg1 $(, $arg)* ,))
};
}
macro_rules! ffi_try_impl {
( $($function:ident)::*( $($arg:expr,)*) ) => {{
let mut err: *mut ::libc::c_char = ::std::ptr::null_mut();
let result = $($function)::*($($arg,)* &mut err);
if !err.is_null() {
return Err(Error::new($crate::ffi_util::error_message(err)));
}
result
}};
}
pub trait CStrLike {
type Baked: std::ops::Deref<Target = CStr>;
type Error: std::fmt::Debug + std::fmt::Display;
fn bake(self) -> Result<Self::Baked, Self::Error>;
fn into_c_string(self) -> Result<CString, Self::Error>;
}
impl CStrLike for &str {
type Baked = CString;
type Error = std::ffi::NulError;
fn bake(self) -> Result<Self::Baked, Self::Error> {
CString::new(self)
}
fn into_c_string(self) -> Result<CString, Self::Error> {
CString::new(self)
}
}
impl CStrLike for &String {
type Baked = CString;
type Error = std::ffi::NulError;
fn bake(self) -> Result<Self::Baked, Self::Error> {
CString::new(self.as_bytes())
}
fn into_c_string(self) -> Result<CString, Self::Error> {
CString::new(self.as_bytes())
}
}
impl CStrLike for &CStr {
type Baked = Self;
type Error = std::convert::Infallible;
fn bake(self) -> Result<Self::Baked, Self::Error> {
Ok(self)
}
fn into_c_string(self) -> Result<CString, Self::Error> {
Ok(self.to_owned())
}
}
impl CStrLike for CString {
type Baked = CString;
type Error = std::convert::Infallible;
fn bake(self) -> Result<Self::Baked, Self::Error> {
Ok(self)
}
fn into_c_string(self) -> Result<CString, Self::Error> {
Ok(self)
}
}
impl<'a> CStrLike for &'a CString {
type Baked = &'a CStr;
type Error = std::convert::Infallible;
fn bake(self) -> Result<Self::Baked, Self::Error> {
Ok(self)
}
fn into_c_string(self) -> Result<CString, Self::Error> {
Ok(self.clone())
}
}
#[test]
fn test_c_str_like_bake() {
fn test<S: CStrLike>(value: S) -> Result<usize, S::Error> {
value
.bake()
.map(|value| unsafe { libc::strlen(value.as_ptr()) })
}
assert_eq!(Ok(3), test("foo")); assert_eq!(Ok(3), test(&String::from("foo"))); assert_eq!(Ok(3), test(CString::new("foo").unwrap().as_ref())); assert_eq!(Ok(3), test(&CString::new("foo").unwrap())); assert_eq!(Ok(3), test(CString::new("foo").unwrap())); assert_eq!(3, test("foo\0bar").err().unwrap().nul_position());
}
#[test]
fn test_c_str_like_into() {
fn test<S: CStrLike>(value: S) -> Result<CString, S::Error> {
value.into_c_string()
}
let want = CString::new("foo").unwrap();
assert_eq!(Ok(want.clone()), test("foo")); assert_eq!(Ok(want.clone()), test(&String::from("foo"))); assert_eq!(
Ok(want.clone()),
test(CString::new("foo").unwrap().as_ref())
); assert_eq!(Ok(want.clone()), test(&CString::new("foo").unwrap())); assert_eq!(Ok(want), test(CString::new("foo").unwrap())); assert_eq!(3, test("foo\0bar").err().unwrap().nul_position());
}