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
/// Wrapper types and helpers for working with the Janus FFI layer.

use glib_sys as glib;
use libc;
use serde::ser::{self, Serialize, Serializer};
use std::ffi::CStr;
use std::ops::Deref;
use std::os::raw::c_char;

/// A C-style string which was allocated using glibc. Derefs to a `CStr`.
#[derive(Debug)]
pub struct GLibString {
    ptr: *const CStr,
}

impl GLibString {
    /// Creates a `GLibString` from a glibc-allocated pointer to a C-style string.
    pub unsafe fn from_chars(chars: *const c_char) -> Option<Self> {
        chars.as_ref().map(|c| Self { ptr: CStr::from_ptr(c) })
    }
}

impl Deref for GLibString {
    type Target = CStr;

    fn deref(&self) -> &CStr {
        unsafe { &*self.ptr }
    }
}

impl Drop for GLibString {
    fn drop(&mut self) {
        unsafe { glib::g_free(self.ptr as *mut _) }
    }
}

impl Serialize for GLibString {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        match self.to_str() {
            Ok(s) => serializer.serialize_str(s),
            Err(e) => Err(ser::Error::custom(e))
        }
    }
}

unsafe impl Send for GLibString {}
unsafe impl Sync for GLibString {}

/// A C-style string which was allocated using libc. Derefs to a `CStr`.
#[derive(Debug)]
pub struct LibcString {
    ptr: *const CStr,
}

impl LibcString {
    /// Creates a `LibcString` from a libc-allocated pointer to a C-style string.
    pub unsafe fn from_chars(chars: *const c_char) -> Option<Self> {
        chars.as_ref().map(|c| Self { ptr: CStr::from_ptr(c) })
    }
}

impl Deref for LibcString {
    type Target = CStr;

    fn deref(&self) -> &CStr {
        unsafe { &*self.ptr }
    }
}

impl Drop for LibcString {
    fn drop(&mut self) {
        unsafe { libc::free(self.ptr as *mut _) }
    }
}

impl Serialize for LibcString {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        match self.to_str() {
            Ok(s) => serializer.serialize_str(s),
            Err(e) => Err(ser::Error::custom(e))
        }
    }
}

unsafe impl Send for LibcString {}
unsafe impl Sync for LibcString {}