use crate::repr_c::ReprC;
use serde_derive::{Deserialize, Serialize};
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<Self, Self::Error> {
if c_repr.is_null() {
return Err(StringError::Null(
"String could not be constructed from C null pointer".to_owned(),
));
}
Ok(CStr::from_ptr(c_repr).to_str()?.to_owned())
}
}
#[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.to_string())
}
}
impl From<NulError> for StringError {
fn from(e: NulError) -> Self {
StringError::Null(e.to_string())
}
}
impl From<IntoStringError> for StringError {
fn from(e: IntoStringError) -> Self {
StringError::IntoString(e.to_string())
}
}