Skip to main content

hs_bindgen_traits/
str.rs

1//! This module defines convenient traits to let user-defined function take as
2//! argument or return type either `CString`, `&CStr`, `String` or `&str`
3
4use crate::{FromReprC, FromReprRust};
5use std::ffi::{c_char, CStr, CString};
6
7impl FromReprRust<*const c_char> for CString {
8    #[inline]
9    fn from(ptr: *const c_char) -> Self {
10        let r: &str = FromReprRust::from(ptr);
11        CString::new(r).unwrap()
12    }
13}
14
15impl FromReprRust<*const c_char> for &CStr {
16    #[inline]
17    #[allow(clippy::not_unsafe_ptr_arg_deref)]
18    fn from(ptr: *const c_char) -> Self {
19        unsafe { CStr::from_ptr(ptr) }
20    }
21}
22
23impl FromReprRust<*const c_char> for String {
24    #[inline]
25    fn from(ptr: *const c_char) -> Self {
26        let r: &str = FromReprRust::from(ptr);
27        r.to_string()
28    }
29}
30
31impl FromReprRust<*const c_char> for &str {
32    #[inline]
33    fn from(ptr: *const c_char) -> Self {
34        let r: &CStr = FromReprRust::from(ptr);
35        r.to_str().unwrap()
36    }
37}
38
39impl FromReprC<CString> for *const c_char {
40    #[inline]
41    fn from(s: CString) -> Self {
42        let x = s.as_ptr();
43        // FIXME: this pattern is somehow duplicated in `vec` module and should
44        // rather live behind in a `AsPtr` trait, similar to the one defined by
45        // https://crates.io/crates/ptrplus
46        std::mem::forget(s);
47        x
48    }
49}
50
51impl FromReprC<String> for *const c_char {
52    #[inline]
53    fn from(s: String) -> Self {
54        FromReprC::from(CString::new(s).unwrap())
55    }
56}
57
58#[test]
59fn _1() {
60    let x = "hello"; // FIXME: use Arbitrary crate
61    let y: &str = FromReprRust::from(FromReprC::from(x.to_string()));
62    assert!(x == y);
63}