use crate::error::ConversionError;
use crate::kapi;
use std::ffi::{c_void, CStr};
use std::fmt;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SymbolError {
#[error("Embedded NUL character found at index {0}")]
InternalNul(usize),
#[error("String too long ({0} chars)")]
StringTooLong(usize),
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Symbol(*const i8);
impl PartialEq for Symbol {
fn eq(&self, other: &Symbol) -> bool {
std::ptr::eq(self.0, other.0)
}
}
impl Eq for Symbol {}
impl std::hash::Hash for Symbol {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(self.0, state)
}
}
extern "C" {
fn memchr(cx: *const c_void, c: i32, n: usize) -> *mut c_void;
}
impl Symbol {
pub fn new<T: AsRef<str>>(st: T) -> Result<Symbol, SymbolError> {
let s = st.as_ref();
if s.len() > isize::MAX as usize {
return Err(SymbolError::StringTooLong(s.len()));
}
let first_nul = unsafe { memchr(s.as_ptr() as *const c_void, 0, s.len()) };
if !first_nul.is_null() {
return Err(SymbolError::InternalNul(first_nul as usize - s.as_ptr() as usize));
}
Ok(Symbol(unsafe { kapi::sn(s.as_ptr() as *const i8, s.len() as i32) }))
}
pub unsafe fn new_unchecked<T: AsRef<str>>(st: T) -> Symbol {
let s = st.as_ref();
Symbol(kapi::sn(s.as_ptr() as *const i8, s.len() as i32))
}
pub fn try_as_str(&self) -> Result<&'static str, ConversionError> {
Ok(unsafe { CStr::from_ptr(self.0).to_str()? })
}
pub unsafe fn as_str_unchecked(&self) -> &'static str {
std::str::from_utf8_unchecked(CStr::from_ptr(self.0).to_bytes())
}
}
impl From<Symbol> for *const i8 {
fn from(sym: Symbol) -> Self {
sym.0
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let cs = unsafe { CStr::from_ptr(self.0) };
write!(f, "{}", String::from_utf8_lossy(cs.to_bytes()))
}
}
pub fn symbol(s: &str) -> Symbol {
Symbol::new(s).unwrap()
}