use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use eggfetch_core::Client;
pub struct ClientBuilderHandle(pub(crate) Option<eggfetch_core::ClientBuilder>);
pub struct ClientHandle(pub(crate) Client);
pub struct RequestHandle(pub(crate) Option<eggfetch_core::RequestBuilder>);
pub struct ResponseHandle {
pub(crate) status: u16,
pub(crate) url: String,
pub(crate) headers: Vec<(String, String)>,
pub(crate) body: bytes::Bytes,
}
pub struct ErrorHandle {
pub(crate) kind: String,
pub(crate) message: String,
}
#[repr(C)]
pub struct FfiString {
ptr: *mut c_char,
}
impl FfiString {
#[must_use]
pub unsafe fn from_string(s: String) -> Option<Self> {
let c = CString::new(s).ok()?;
Some(Self { ptr: c.into_raw() })
}
#[must_use]
pub unsafe fn from_static(s: &'static str) -> Option<Self> {
Self::from_string(s.to_owned())
}
#[must_use]
pub fn into_raw(self) -> *mut c_char {
let ptr = self.ptr;
let _ = std::mem::ManuallyDrop::new(self);
ptr
}
}
impl Drop for FfiString {
fn drop(&mut self) {
if !self.ptr.is_null() {
unsafe {
drop(CString::from_raw(self.ptr));
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn eggfetch_string_free(s: *mut c_char) {
crate::ffi_guard!((), {
if !s.is_null() {
drop(CString::from_raw(s));
}
});
}
pub(crate) unsafe fn cstr_to_string(ptr: *const c_char) -> Option<String> {
if ptr.is_null() {
None
} else {
String::from_utf8(CStr::from_ptr(ptr).to_bytes().to_vec()).ok()
}
}
#[must_use]
#[allow(clippy::unnecessary_box_returns)]
pub(crate) fn error_to_handle(e: &eggfetch_core::Error) -> Box<ErrorHandle> {
Box::new(ErrorHandle {
kind: e.kind().to_owned(),
message: e.to_string(),
})
}