Skip to content

Commit

Permalink
extendr-api: add as_str_mut
Browse files Browse the repository at this point in the history
this might not make sense for NA strings
for now, there is a `todo!`
  • Loading branch information
CGMossa committed Feb 29, 2024
1 parent fcf64eb commit 44cf5a6
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions extendr-api/src/robj/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,7 @@ impl Robj {
unsafe {
let charsxp = match self.sexptype() {
STRSXP => {
// only allows scalar strings
if self.len() != 1 {
return None;
}
Expand All @@ -613,6 +614,42 @@ impl Robj {
Some(std::str::from_utf8_unchecked(all_bytes))
}
}
/// Get a mutable reference to a scalar string type.
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let robj1 = Robj::from("xyz");
/// let robj2 = Robj::from(1);
/// assert_eq!(robj1.as_str(), Some("xyz"));
/// assert_eq!(robj2.as_str(), None);
/// }
/// ```
pub fn as_str_mut<'a>(&mut self) -> Option<&'a mut str> {
unsafe {
let charsxp = match self.sexptype() {
STRSXP => {
// only allows Scalar strings
if self.len() != 1 {
return None;
}
Some(STRING_ELT(self.get_mut(), 0))
}
CHARSXP => Some(self.get_mut()),
SYMSXP => Some(PRINTNAME(self.get_mut())),
_ => None,
};

let charsxp = charsxp?;
if charsxp == R_NaString {
todo!()
// return Some(<&str>::na());
}

let length = Rf_xlength(charsxp);
let all_bytes = std::slice::from_raw_parts_mut(R_CHAR(charsxp) as _, length as _);
Some(std::str::from_utf8_unchecked_mut(all_bytes))
}
}

/// Get a scalar integer.
/// ```
Expand Down

0 comments on commit 44cf5a6

Please sign in to comment.