use crate::terminated_array;
use core::{
fmt::{self, Debug},
ptr::NonNull,
};
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct TStr {
ptr: NonNull<i8>,
}
impl TStr {
#[inline]
pub fn from_ptr(ptr: NonNull<i8>) -> Self {
Self { ptr }
}
#[inline]
pub fn as_ptr(&self) -> *const i8 {
self.ptr.as_ptr() as _
}
#[inline]
pub unsafe fn as_str<'a>(&self) -> &'a str {
core::str::from_utf8_unchecked(terminated_array::<u8>(self.ptr.as_ptr() as _, 0))
}
#[inline]
pub unsafe fn as_slice<'a>(&self) -> &'a [i8] {
terminated_array(self.ptr.as_ptr() as _, 0)
}
#[inline]
pub unsafe fn len(&self) -> usize {
terminated_array(self.ptr.as_ptr(), 0).len()
}
#[inline]
pub unsafe fn is_empty(&self) -> bool {
*self.ptr.as_ptr() == 0
}
}
impl Debug for TStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe { write!(f, "{:?}", self.as_str()) }
}
}
#[macro_export]
macro_rules! tstr {
( $($tt:tt)* ) => {
$crate::types::TStr::from_ptr(unsafe { core::ptr::NonNull::new_unchecked(core::concat!($($tt)*, "\x00").as_ptr() as _) })
}
}