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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
use failure::{ensure, format_err, Error, ResultExt};

/// A macro to convert a `std::String` to a C-compatible representation : a raw pointer to libc::c_char.
/// After calling this function, the caller is responsible for releasing the memory.
/// The [`take_back_c_string!`] macro can be used for releasing the memory.
#[macro_export]
macro_rules! convert_to_c_string {
    ($string:expr) => {
        $crate::convert_to_c_string_result!($string)?
    };
}

/// A macro to convert a `std::String` to a C-compatible representation a raw pointer to libc::c_char
/// wrapped in a Result enum.
/// After calling this function, the caller is responsible for releasing the memory.
/// The [`take_back_c_string!`] macro can be used for releasing the memory.  
#[macro_export]
macro_rules! convert_to_c_string_result {
    ($string:expr) => {
        std::ffi::CString::c_repr_of($string).map(|s| {
            use $crate::RawPointerConverter;
            s.into_raw_pointer() as *const libc::c_char
        })
    };
}

/// A macro to convert a `Vec<String>` to a C-compatible representation : a raw pointer to a CStringArray
/// After calling this function, the caller is responsible for releasing the memory.
/// The [`take_back_c_string_array!`] macro can be used for releasing the memory.
#[macro_export]
macro_rules! convert_to_c_string_array {
    ($string_vec:expr) => {{
        use $crate::RawPointerConverter;
        $crate::CStringArray::c_repr_of($string_vec)?.into_raw_pointer()
    }};
}

/// A macro to convert a `Vec<String>` to a C-compatible representation : a raw pointer to a CStringArray
/// After calling this function, the caller is responsible for releasing the memory.
/// The [`take_back_c_string_array!`] macro can be used for releasing the memory.
#[macro_export]
macro_rules! convert_to_nullable_c_string_array {
    ($opt:expr) => {
        if let Some(s) = $opt {
            $crate::convert_to_c_string_array!(s)
        } else {
            null()
        }
    };
}

/// A macro to convert an `Option<String>` to a C-compatible representation : a raw pointer to libc::c_char if the Option enum is of variant Some,
/// or a null pointer if the Option enum is of variant None.  
#[macro_export]
macro_rules! convert_to_nullable_c_string {
    ($opt:expr) => {
        if let Some(s) = $opt {
            $crate::convert_to_c_string!(s)
        } else {
            null()
        }
    };
}

/// Retakes the ownership of the memory pointed to by a raw pointer to a libc::c_char
#[macro_export]
macro_rules! take_back_c_string {
    ($pointer:expr) => {{
        use $crate::RawPointerConverter;
        let _ = unsafe { std::ffi::CString::from_raw_pointer($pointer) };
    }};
}

/// Retakes the ownership of the memory pointed to by a raw pointer to a libc::c_char, checking first if the pointer is not null.
#[macro_export]
macro_rules! take_back_nullable_c_string {
    ($pointer:expr) => {
        if !$pointer.is_null() {
            $crate::take_back_c_string!($pointer)
        }
    };
}

/// Retakes the ownership of the memory storing an array of C-compatible strings
#[macro_export]
macro_rules! take_back_c_string_array {
    ($pointer:expr) => {{
        use $crate::RawPointerConverter;
        let _ = unsafe { $crate::CStringArray::from_raw_pointer($pointer) };
    }};
}

/// Retakes the ownership of the memory storing an array of C-compatible strings, checking first if the provided pointer is not null.
#[macro_export]
macro_rules! take_back_nullable_c_string_array {
    ($pointer:expr) => {
        if !$pointer.is_null() {
            $crate::take_back_c_string_array!($pointer)
        }
    };
}

/// Unsafely creates an owned string from a pointer to a nul-terminated array of bytes.
#[macro_export]
macro_rules! create_rust_string_from {
    ($pointer:expr) => {{
        use $crate::RawBorrow;
        unsafe { std::ffi::CStr::raw_borrow($pointer) }?
            .to_str()
            .context("Could not convert pointer to rust str")?
            .to_owned()
    }};
}

/// Unsafely creates an optional owned string from a pointer to a nul-terminated array of bytes.
#[macro_export]
macro_rules! create_optional_rust_string_from {
    ($pointer:expr) => {
        match unsafe { $pointer.as_ref() } {
            Some(thing) => Some($crate::create_rust_string_from!(thing)),
            None => None,
        }
    };
}

/// Unsafely creates an array of owned string from a pointer to a CStringArray.
#[macro_export]
macro_rules! create_rust_vec_string_from {
    ($pointer:expr) => {{
        use $crate::RawBorrow;
        unsafe { $crate::CStringArray::raw_borrow($pointer) }?.as_rust()?
    }};
}

/// Unsafely creates an optional array of owned string from a pointer to a CStringArray.
#[macro_export]
macro_rules! create_optional_rust_vec_string_from {
    ($pointer:expr) => {
        match unsafe { $pointer.as_ref() } {
            Some(thing) => Some($crate::create_rust_vec_string_from!(thing)),
            None => None,
        }
    };
}

macro_rules! impl_c_repr_of_for {
    ($typ:ty) => {
        impl CReprOf<$typ> for $typ {
            fn c_repr_of(input: $typ) -> Result<$typ, Error> {
                Ok(input)
            }
        }
    };

    ($from_typ:ty, $to_typ:ty) => {
        impl CReprOf<$from_typ> for $to_typ {
            fn c_repr_of(input: $from_typ) -> Result<$to_typ, Error> {
                Ok(input as $to_typ)
            }
        }
    };
}

/// implements a noop implementation of the CDrop trait for a given type.
macro_rules! impl_c_drop_for {
    ($typ:ty) => {
        impl CDrop for $typ {
            fn do_drop(&mut self) -> Result<(), Error> {
                Ok(())
            }
        }
    };
}

macro_rules! impl_as_rust_for {
    ($typ:ty) => {
        impl AsRust<$typ> for $typ {
            fn as_rust(&self) -> Result<$typ, Error> {
                Ok(*self)
            }
        }
    };

    ($from_typ:ty, $to_typ:ty) => {
        impl AsRust<$to_typ> for $from_typ {
            fn as_rust(&self) -> Result<$to_typ, Error> {
                Ok(*self as $to_typ)
            }
        }
    };
}

pub fn point_to_string(pointer: *mut *const libc::c_char, string: String) -> Result<(), Error> {
    unsafe { *pointer = std::ffi::CString::c_repr_of(string)?.into_raw_pointer() }
    Ok(())
}

/// Trait showing that the struct implementing it is a `repr(C)` compatible view of the parametrized
/// type that can be created from an object of this type.
pub trait CReprOf<T>: Sized + CDrop {
    fn c_repr_of(input: T) -> Result<Self, Error>;
}

/// Trait showing that the C-like struct implementing it can free up its part of memory that are not
/// managed by Rust.
pub trait CDrop {
    fn do_drop(&mut self) -> Result<(), Error>;
}

/// Trait showing that the struct implementing it is a `repr(C)` compatible view of the parametrized
/// type and that an instance of the parametrized type can be created form this struct
pub trait AsRust<T> {
    fn as_rust(&self) -> Result<T, Error>;
}

/// Trait representing the creation of a raw pointer from a struct and the recovery of said pointer.
///
/// The `from_raw_pointer` function should be used only on pointers obtained thought the
/// `into_raw_pointer` method (and is thus unsafe as we don't have any way to get insurance of that
/// from the compiler).
///
/// The `from_raw_pointer` effectively takes back ownership of the pointer. If you didn't create the
/// pointer yourself, please use the `as_ref` method on the raw pointer to borrow it
///
/// A generic implementation of this trait exist for every struct, it will use a `Box` to create the
/// pointer. There is also a special implementation available in order to create a
/// `*const libc::c_char` from a CString.
pub trait RawPointerConverter<T>: Sized {
    fn into_raw_pointer(self) -> *const T;
    unsafe fn from_raw_pointer(input: *const T) -> Result<Self, Error>;

    unsafe fn drop_raw_pointer(input: *const T) -> Result<(), Error> {
        T::from_raw_pointer(input).map(|_| ())
    }
}

/// Trait to create borrowed references to type T, from a raw pointer to a T
pub trait RawBorrow<T> {
    unsafe fn raw_borrow<'a>(input: *const T) -> Result<&'a Self, Error>;
}

/// Trait to create mutable borrowed references to type T, from a raw pointer to a T
pub trait RawBorrowMut<T> {
    unsafe fn raw_borrow_mut<'a>(input: *mut T) -> Result<&'a mut Self, Error>;
}

/// TODO custom derive instead of generic impl, this would prevent CString from having 2 impls...
/// Trait representing conversion operations from and to owned type T to a raw pointer to T
impl<T> RawPointerConverter<T> for T {
    fn into_raw_pointer(self) -> *const T {
        Box::into_raw(Box::new(self)) as _
    }

    unsafe fn from_raw_pointer(input: *const T) -> Result<T, Error> {
        ensure!(
            !input.is_null(),
            "could not take raw pointer, unexpected null pointer"
        );
        Ok(*Box::from_raw(input as *mut T))
    }
}

/// Trait that allows obtaining a borrowed reference to a type T from a raw pointer to T
impl<T> RawBorrow<T> for T {
    unsafe fn raw_borrow<'a>(input: *const T) -> Result<&'a Self, Error> {
        input
            .as_ref()
            .ok_or_else(|| format_err!("could not borrow, unexpected null pointer"))
    }
}

/// Trait that allows obtaining a mutable borrowed reference to a type T from a raw pointer to T
impl<T> RawBorrowMut<T> for T {
    unsafe fn raw_borrow_mut<'a>(input: *mut T) -> Result<&'a mut Self, Error> {
        input
            .as_mut()
            .ok_or_else(|| format_err!("could not borrow, unexpected null pointer"))
    }
}

impl RawPointerConverter<libc::c_void> for std::ffi::CString {
    fn into_raw_pointer(self) -> *const libc::c_void {
        self.into_raw() as _
    }

    unsafe fn from_raw_pointer(input: *const libc::c_void) -> Result<Self, Error> {
        ensure!(
            !input.is_null(),
            "could not take raw pointer, unexpected null pointer"
        );
        Ok(std::ffi::CString::from_raw(input as *mut libc::c_char))
    }
}

impl RawPointerConverter<libc::c_char> for std::ffi::CString {
    fn into_raw_pointer(self) -> *const libc::c_char {
        self.into_raw() as _
    }

    unsafe fn from_raw_pointer(input: *const libc::c_char) -> Result<Self, Error> {
        ensure!(
            !input.is_null(),
            "could not take raw pointer, unexpected null pointer"
        );
        Ok(std::ffi::CString::from_raw(input as *mut libc::c_char))
    }
}

impl RawBorrow<libc::c_char> for std::ffi::CStr {
    unsafe fn raw_borrow<'a>(input: *const libc::c_char) -> Result<&'a Self, Error> {
        ensure!(
            !input.is_null(),
            "could not borrow, unexpected null pointer"
        );
        Ok(Self::from_ptr(input))
    }
}

impl_c_drop_for!(usize);
impl_c_drop_for!(u8);
impl_c_drop_for!(i16);
impl_c_drop_for!(u16);
impl_c_drop_for!(i32);
impl_c_drop_for!(u32);
impl_c_drop_for!(i64);
impl_c_drop_for!(u64);
impl_c_drop_for!(f32);
impl_c_drop_for!(f64);
impl_c_drop_for!(std::ffi::CString);

impl_c_repr_of_for!(usize);
impl_c_repr_of_for!(i16);
impl_c_repr_of_for!(u16);
impl_c_repr_of_for!(i32);
impl_c_repr_of_for!(u32);
impl_c_repr_of_for!(i64);
impl_c_repr_of_for!(u64);
impl_c_repr_of_for!(f32);
impl_c_repr_of_for!(f64);

impl_c_repr_of_for!(usize, i32);

impl CReprOf<bool> for u8 {
    fn c_repr_of(input: bool) -> Result<u8, Error> {
        Ok(if input { 1 } else { 0 })
    }
}

impl CReprOf<String> for std::ffi::CString {
    fn c_repr_of(input: String) -> Result<Self, Error> {
        std::ffi::CString::new(input)
            .context("Could not convert String to C Repr")
            .map_err(|e| e.into())
    }
}

impl_as_rust_for!(usize);
impl_as_rust_for!(i16);
impl_as_rust_for!(u16);
impl_as_rust_for!(i32);
impl_as_rust_for!(u32);
impl_as_rust_for!(i64);
impl_as_rust_for!(u64);
impl_as_rust_for!(f32);
impl_as_rust_for!(f64);

impl_as_rust_for!(i32, usize);

impl AsRust<bool> for u8 {
    fn as_rust(&self) -> Result<bool, Error> {
        Ok((*self) != 0)
    }
}

impl AsRust<String> for std::ffi::CStr {
    fn as_rust(&self) -> Result<String, Error> {
        self.to_str().map(|s| s.to_owned()).map_err(|e| e.into())
    }
}