use super::*;
use extendr_ffi::{R_BlankString, R_NaString, R_NilValue, Rf_xlength, R_CHAR, SEXPTYPE, TYPEOF};
#[derive(Clone)]
pub struct Rstr {
pub(crate) robj: Robj,
}
pub(crate) unsafe fn charsxp_to_str(charsxp: SEXP) -> Option<&'static str> {
assert_eq!(TYPEOF(charsxp), SEXPTYPE::CHARSXP);
if charsxp == R_NilValue {
None
} else if charsxp == R_NaString {
Some(<&str>::na())
} else if charsxp == R_BlankString {
Some("")
} else {
let length = Rf_xlength(charsxp);
let all_bytes =
std::slice::from_raw_parts(R_CHAR(charsxp).cast(), length.try_into().unwrap());
Some(std::str::from_utf8_unchecked(all_bytes))
}
}
impl Rstr {
#[deprecated(since = "0.8.1", note = "Use `Rstr::from()` or `.into()` instead")]
pub fn from_string(val: &str) -> Self {
Rstr {
robj: unsafe { Robj::from_sexp(str_to_character(val)) },
}
}
#[deprecated(
since = "0.8.1",
note = "Use `.as_ref()` or rely on `Deref` coercion instead"
)]
pub fn as_str(&self) -> &str {
self.into()
}
}
impl AsRef<str> for Rstr {
fn as_ref(&self) -> &str {
self.into()
}
}
impl From<String> for Rstr {
fn from(s: String) -> Self {
Self::from(s.as_str())
}
}
impl From<&str> for Rstr {
fn from(s: &str) -> Self {
Rstr {
robj: unsafe { Robj::from_sexp(str_to_character(s)) },
}
}
}
impl From<&Rstr> for &str {
fn from(value: &Rstr) -> Self {
unsafe {
let charsxp = value.robj.get();
rstr::charsxp_to_str(charsxp).unwrap()
}
}
}
impl From<Option<String>> for Rstr {
fn from(value: Option<String>) -> Self {
if let Some(string) = value {
Self::from(string)
} else {
Self { robj: na_string() }
}
}
}
impl Deref for Rstr {
type Target = str;
fn deref(&self) -> &Self::Target {
self.into()
}
}
impl PartialEq<Rstr> for Rstr {
fn eq(&self, other: &Rstr) -> bool {
unsafe { self.robj.get() == other.robj.get() }
}
}
impl PartialEq<str> for Rstr {
fn eq(&self, other: &str) -> bool {
self.as_ref() == other
}
}
impl PartialEq<Rstr> for &str {
fn eq(&self, other: &Rstr) -> bool {
*self == other.as_ref()
}
}
impl PartialEq<&str> for Rstr {
fn eq(&self, other: &&str) -> bool {
self.as_ref() == *other
}
}
impl PartialEq<Rstr> for &&str {
fn eq(&self, other: &Rstr) -> bool {
**self == other.as_ref()
}
}
impl std::fmt::Debug for Rstr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_na() {
write!(f, "NA_CHARACTER")
} else {
let s: &str = self.as_ref();
write!(f, "{:?}", s)
}
}
}
impl std::fmt::Display for Rstr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s: &str = self.as_ref();
write!(f, "{}", s)
}
}
impl CanBeNA for Rstr {
fn is_na(&self) -> bool {
unsafe { self.robj.get() == R_NaString }
}
fn na() -> Self {
unsafe {
Self {
robj: Robj::from_sexp(R_NaString),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate as extendr_api;
#[test]
fn test_rstr_as_char() {
test! {
let chr = r!(Rstr::from("xyz"));
let x = chr.as_char().unwrap();
assert_eq!(x.as_ref(), "xyz");
}
}
}