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
use repr_c::ReprC;
use std::error::Error;
use std::ffi::{CStr, IntoStringError, NulError};
use std::os::raw::c_char;
use std::str::Utf8Error;
impl ReprC for String {
type C = *const c_char;
type Error = StringError;
unsafe fn clone_from_repr_c(c_repr: Self::C) -> Result<String, StringError> {
Ok(if c_repr.is_null() {
String::default()
} else {
from_c_str(c_repr)?
})
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub enum StringError {
Utf8(String),
Null(String),
IntoString(String),
}
impl From<Utf8Error> for StringError {
fn from(e: Utf8Error) -> Self {
StringError::Utf8(e.description().to_owned())
}
}
impl From<NulError> for StringError {
fn from(e: NulError) -> Self {
StringError::Null(e.description().to_owned())
}
}
impl From<IntoStringError> for StringError {
fn from(e: IntoStringError) -> Self {
StringError::IntoString(e.description().to_owned())
}
}
#[inline]
pub unsafe fn from_c_str(ptr: *const c_char) -> Result<String, StringError> {
if ptr.is_null() {
return Err(StringError::Null(
"String could not be constructed from C null pointer".to_owned(),
));
}
Ok(CStr::from_ptr(ptr).to_str()?.to_owned())
}