Skip to main content

try_charsxp_to_str

Function try_charsxp_to_str 

Source
pub(crate) unsafe fn try_charsxp_to_str(
    charsxp: SEXP,
) -> Result<&'static str, SexpError>
Expand description

Read a CHARSXP as Rust text, translating it to UTF-8 when its encoding requires.

UTF-8 strings, ASCII strings and native strings in a UTF-8 session borrow directly from the CHARSXP via R_CHAR + LENGTH. Latin-1 strings, and native non-ASCII strings in a session whose locale isn’t UTF-8, use Rf_translateCharUTF8; that buffer lives on R’s memory stack for the enclosing .Call. The first native translation of the session queues a warning (encoding::warn_native_translation).

A string marked with R’s bytes encoding is not text, and a string read without translation whose bytes are not valid UTF-8 has no str: both are an SexpError::InvalidValue (BYTES_REASON, INVALID_UTF8_REASON), which an argument conversion reports as an argument error. Every caller that returns a Result reads strings through this; charsxp_to_str_or_panic is for the few that cannot.

§Safety

  • charsxp must be a valid CHARSXP (not NA_STRING, not null).
  • The returned &str is only valid as long as R doesn’t GC the CHARSXP, and, for a translated string, until the enclosing .Call returns.