use core::{fmt, ops::Deref};

use safer_ffi::prelude::char_p;

/// A `String` with exactly one null byte, in terminating position.
///
/// This, thus, allows it to offer a `char_p::Ref<'_>` zero-cost getter.
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct ZString(String);

impl From<char_p::Box> for ZString {
    #[inline]
    fn from(s: char_p::Box) -> ZString {
        let mut s: String = s.into_string();
        // `.into_string()` strips the terminating `\0` for convenience.
        s.push('\0');
        ZString(s)
    }
}

impl From<ZString> for char_p::Box {
    #[inline]
    fn from(s: ZString) -> char_p::Box {
        char_p::new(s.0)
    }
}

impl TryFrom<String> for ZString {
    type Error = ::safer_ffi::char_p::InvalidNulTerminator<String>;

    #[inline]
    fn try_from(value: String) -> Result<ZString, Self::Error> {
        char_p::Box::try_from(value).map(ZString::from)
    }
}

#[allow(nonstandard_style)]
#[derive(Debug, Hash, Eq, PartialEq, Ord, PartialOrd, ::bytemuck::TransparentWrapper)]
#[repr(transparent)]
/// Same as [`ZString`], but for [`str`].
pub struct zstr(str);

impl<'r> From<char_p::Ref<'r>> for &'r zstr {
    #[inline]
    fn from(s: char_p::Ref<'r>) -> &'r zstr {
        ::bytemuck::TransparentWrapper::wrap_ref(s.to_str_with_null())
    }
}

impl<'r> From<&'r zstr> for char_p::Ref<'r> {
    #[inline]
    fn from(s: &'r zstr) -> char_p::Ref<'r> {
        char_p::Ref::try_from(&s.0).unwrap()
    }
}

impl Deref for ZString {
    type Target = zstr;

    #[inline]
    fn deref(self: &ZString) -> &zstr {
        ::bytemuck::TransparentWrapper::wrap_ref(&self.0[..])
    }
}

impl Deref for zstr {
    type Target = str;

    #[inline]
    fn deref(self: &zstr) -> &str {
        // Skips the null terminator.
        &self.0[..self.0.len() - 1]
    }
}

// Extra conversions.
// Note: anything involving `str::method()` goes through `zstr::deref()`,
// which in turn *skips* the terminating null byte.

impl fmt::Display for ZString {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        str::fmt(self, f)
    }
}

impl ZString {
    /// More efficient than `Display`'s `.to_string()`.
    #[allow(clippy::inherent_to_string_shadow_display)]
    #[inline]
    pub fn to_string(&self) -> String {
        str::to_string(self)
    }
}

impl fmt::Display for zstr {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        str::fmt(self, f)
    }
}

impl zstr {
    /// More efficient than `Display`'s `.to_string()`.
    #[allow(clippy::inherent_to_string_shadow_display)]
    #[inline]
    pub fn to_string(&self) -> String {
        str::to_string(self)
    }
}

impl ToOwned for zstr {
    type Owned = ZString;

    #[inline]
    fn to_owned(self: &zstr) -> ZString {
        ZString(self.0.to_owned())
    }
}

impl ::core::borrow::Borrow<zstr> for ZString {
    #[inline]
    fn borrow(self: &ZString) -> &zstr {
        self
    }
}
