Skip to main content

miniextendr_api/
nullable.rs

1//! [`Nullable<T>`]: an optional value whose `None` is `NULL` in R.
2//!
3//! An `Option<T>` return converts through `Option<T>`'s own [`IntoR`]: `None`
4//! is `NULL` for a vector, list or class, but `NA` for a scalar
5//! (`Option<i32>` gives `NA_integer_`), because R stores a missing scalar as
6//! `NA`. Where `None` means that there is no value at all, whatever `T` is,
7//! return `Nullable<T>`: `Some(v)` converts as `v` does, and `None` is `NULL`.
8//! The [`RIterator` adapter](crate::RIterator) uses it for the end of
9//! iteration, which an `NA` item would be indistinguishable from.
10//!
11//! ```ignore
12//! use miniextendr_api::{miniextendr, Nullable};
13//!
14//! #[miniextendr]
15//! pub fn first_even(xs: Vec<i32>) -> Nullable<i32> {
16//!     Nullable(xs.into_iter().find(|x| x % 2 == 0))
17//! }
18//! // R: first_even(c(1L, 4L)) → 4L
19//! //    first_even(c(1L, 3L)) → NULL  (an `Option<i32>` return gives NA_integer_)
20//! ```
21//!
22//! It reads from R as `Option<T>` does ([`TryFromSexp`]): `NULL` and `NA`
23//! are `None`. That makes it an `#[r_data]` field type of an
24//! `#[derive(ExternalPtr)]` struct, whose getter reads `NULL` for `None` and
25//! whose setter stores `None` for `NULL` (#2270); an `Option<T>` field reads
26//! `NA` for a scalar `None`, unless it is marked `#[r_data(null_if_none)]`.
27//! As a `#[miniextendr]` argument it behaves exactly as `Option<T>` (#2294):
28//! the same R-side checks and conversion message (`'x' must be NULL or ...`),
29//! and `coerce`, `no_na` and `match_arg` look through it. An optional
30//! argument is usually spelled `Option<T>`.
31//!
32//! With the `serde` feature, `Nullable<T>` serializes and deserializes as
33//! `Option<T>` does, so a serde struct can hold one.
34
35use crate::SEXP;
36use crate::from_r::prepared::{Arms, Prepared};
37use crate::from_r::{NativeBorrow, TryFromSexp};
38use crate::into_r::IntoR;
39
40/// An optional value that R receives as `NULL` when `None`, whatever `T` is,
41/// and that reads `NULL` or `NA` from R as `None`. See the
42/// [module docs](self).
43#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
    Nullable<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "Nullable",
            &&self.0)
    }
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
    Nullable<T> {
    #[inline]
    fn clone(&self) -> Self { Nullable(::core::clone::Clone::clone(&self.0)) }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy> ::core::marker::Copy for
    Nullable<T> {
}Copy, #[automatically_derived]impl<T: ::core::cmp::PartialEq>
    ::core::marker::StructuralPartialEq for Nullable<T> {
}
#[automatically_derived]impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq
    for Nullable<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl<T: ::core::cmp::Eq> ::core::cmp::Eq for
    Nullable<T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<T>>;
    }
}Eq, #[automatically_derived]impl<T: ::core::cmp::PartialOrd>
    ::core::cmp::PartialOrd for Nullable<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}PartialOrd, #[automatically_derived]impl<T: ::core::cmp::Ord> ::core::cmp::Ord for
    Nullable<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord, #[automatically_derived]impl<T: ::core::hash::Hash> ::core::hash::Hash for
    Nullable<T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]impl<T: ::core::default::Default>
    ::core::default::Default for Nullable<T> {
    #[inline]
    fn default() -> Self { Nullable(::core::default::Default::default()) }
}Default)]
44pub struct Nullable<T>(pub Option<T>);
45
46impl<T> From<Option<T>> for Nullable<T> {
47    #[inline]
48    fn from(value: Option<T>) -> Self {
49        Self(value)
50    }
51}
52
53// region: IntoR
54
55impl<T: IntoR> IntoR for Nullable<T> {
56    type Error = T::Error;
57    #[inline]
58    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
59        match self.0 {
60            Some(v) => v.try_into_sexp(),
61            None => Ok(SEXP::nil()),
62        }
63    }
64    #[inline]
65    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
66        match self.0 {
67            Some(v) => unsafe { v.try_into_sexp_unchecked() },
68            None => Ok(SEXP::nil()),
69        }
70    }
71    #[inline]
72    fn into_sexp(self) -> SEXP {
73        match self.0 {
74            Some(v) => v.into_sexp(),
75            None => SEXP::nil(),
76        }
77    }
78    #[inline]
79    unsafe fn into_sexp_unchecked(self) -> SEXP {
80        match self.0 {
81            Some(v) => unsafe { v.into_sexp_unchecked() },
82            None => SEXP::nil(),
83        }
84    }
85}
86// endregion
87
88// region: TryFromSexp
89
90/// Reads as `Option<T>` does: `NULL` and `NA` are `None` (#2270).
91impl<T> TryFromSexp for Nullable<T>
92where
93    Option<T>: TryFromSexp,
94{
95    const NATIVE_BORROW: Option<NativeBorrow> = <Option<T> as TryFromSexp>::NATIVE_BORROW;
96    const CHARACTER_ONLY: bool = <Option<T> as TryFromSexp>::CHARACTER_ONLY;
97    #[doc(hidden)]
98    const __MX_EXPECTATION: Option<&'static str> = <Option<T> as TryFromSexp>::__MX_EXPECTATION;
99
100    type Error = <Option<T> as TryFromSexp>::Error;
101
102    #[inline]
103    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
104        <Option<T> as TryFromSexp>::try_from_sexp(sexp).map(Self)
105    }
106
107    #[inline]
108    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
109        unsafe { <Option<T> as TryFromSexp>::try_from_sexp_unchecked(sexp) }.map(Self)
110    }
111
112    #[inline]
113    unsafe fn __mx_try_from_rooted(root: crate::Root<'_>) -> Result<Self, Self::Error> {
114        unsafe { <Option<T> as TryFromSexp>::__mx_try_from_rooted(root) }.map(Self)
115    }
116
117    fn __mx_prepare(sexp: SEXP) -> Prepared<Self> {
118        <Option<T> as TryFromSexp>::__mx_prepare(sexp).map(Self, |e| e)
119    }
120
121    fn __mx_materialize(sexp: SEXP, arms: Arms) -> Result<Self, Self::Error> {
122        <Option<T> as TryFromSexp>::__mx_materialize(sexp, arms).map(Self)
123    }
124
125    #[inline]
126    fn __mx_has_na(&self) -> bool {
127        self.0.__mx_has_na()
128    }
129
130    #[inline]
131    fn __mx_input_has_na(&self, input: SEXP) -> bool {
132        self.0.__mx_input_has_na(input)
133    }
134}
135// endregion
136
137// region: serde
138
139/// Serializes as `Option<T>` does.
140#[cfg(feature = "serde")]
141impl<T: ::serde::Serialize> ::serde::Serialize for Nullable<T> {
142    #[inline]
143    fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
144        self.0.serialize(serializer)
145    }
146}
147
148/// Deserializes as `Option<T>` does.
149#[cfg(feature = "serde")]
150impl<'de, T: ::serde::Deserialize<'de>> ::serde::Deserialize<'de> for Nullable<T> {
151    #[inline]
152    fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
153        Option::<T>::deserialize(deserializer).map(Self)
154    }
155}
156// endregion