Skip to main content

aorist_extendr_api/wrapper/
character.rs

1use super::*;
2
3/// Wrapper for creating character objects.
4/// These are used only as the contents of a character
5/// vector.
6///
7/// ```
8/// use extendr_api::prelude::*;
9/// test! {
10///     let chr = r!(Character::from_string("xyz"));
11///     assert_eq!(chr.as_character().unwrap().as_str(), "xyz");
12/// }
13/// ```
14///
15#[derive(Debug, PartialEq, Clone)]
16pub struct Character {
17    pub(crate) robj: Robj,
18}
19
20impl Character {
21    /// Make a character object from a string.
22    pub fn from_string(val: &str) -> Self {
23        unsafe {
24            Character {
25                robj: new_owned(str_to_character(val)),
26            }
27        }
28    }
29
30    /// Get the string from a character object.
31    /// If the string is NA, then the special na_str() is returned.
32    pub fn as_str(&self) -> &str {
33        unsafe {
34            let sexp = self.robj.get();
35            if sexp == R_NaString {
36                na_str()
37            } else {
38                to_str(R_CHAR(sexp) as *const u8)
39            }
40        }
41    }
42}