use core::{
ffi::CStr,
fmt::{Debug, Display},
};
use crate::wrapper::Wrapper;
#[derive(Error)]
#[repr(C)]
pub struct CppException(pub(crate) sdecay_sys::sdecay::Exception);
impl Wrapper for CppException {
type CSide = sdecay_sys::sdecay::Exception;
}
impl CppException {
#[inline]
fn ptr(&self) -> *const sdecay_sys::sdecay::Exception {
core::ptr::from_ref(&self.0)
}
#[inline]
pub fn what(&self) -> &CStr {
let self_ptr = self.ptr();
let what_ptr: *const core::ffi::c_char =
unsafe { sdecay_sys::sdecay::Exception_what(self_ptr) };
unsafe { CStr::from_ptr(what_ptr) }
}
#[cfg(feature = "alloc")]
#[inline]
pub fn what_str(&self) -> alloc::borrow::Cow<'_, str> {
self.what().to_string_lossy()
}
#[cfg(not(feature = "alloc"))]
#[inline]
pub fn what_str(&self) -> &str {
core::str::from_utf8(self.what().to_bytes()).expect("Should be a valid UTF-8 text")
}
}
impl Drop for CppException {
fn drop(&mut self) {
let rf = &mut self.0;
let ptr = core::ptr::from_mut(rf);
unsafe { sdecay_sys::sdecay::Exception_destruct(ptr) };
}
}
impl Debug for CppException {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut d = f.debug_struct("Error");
let message = self.what_str();
d.field("exception", &message).finish()
}
}
impl Display for CppException {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.what_str())
}
}
impl AsRef<CStr> for CppException {
#[inline]
fn as_ref(&self) -> &CStr {
self.what()
}
}