Skip to main content

miniextendr_api/
non_na.rs

1//! [`NonNa<T>`]: a value that holds no R `NA`.
2//!
3//! As a `#[miniextendr]` parameter type, `NonNa<T>` is `#[miniextendr(no_na)]`
4//! written in the type: the parameter converts as `T`, an argument holding an
5//! `NA` is refused with `no_na`'s argument error, and the body receives a
6//! value that says so in its type.
7//!
8//! ```ignore
9//! use miniextendr_api::{NonNa, miniextendr};
10//!
11//! /// `xs` holds no `NA` (and no `NaN`); `sum()` needs no check of its own.
12//! #[miniextendr]
13//! pub fn total(xs: NonNa<Vec<f64>>) -> f64 {
14//!     xs.iter().sum()
15//! }
16//!
17//! /// A string argument: `NA_character_` is refused instead of reaching the
18//! /// body as `""`, as it would for a plain `String`.
19//! #[miniextendr]
20//! pub fn greet(name: NonNa<String>) -> String {
21//!     format!("hello {}", name.unwrap())
22//! }
23//! ```
24//!
25//! "`NA`" is what R's `anyNA()` counts: `NA` in every type, and `NaN` in
26//! doubles and complex numbers. The generated R wrapper checks it first
27//! (`!anyNA(x)`, the `no_na` guard), and the C wrapper checks the argument
28//! again before converting it, so a `.Call()` that skips the R wrapper cannot
29//! hand the body an `NA` either. A reading marker (`AsNumeric`, ...) is also
30//! asked after its conversion, as under `no_na` (`"NA"` strings, blank
31//! cells). The custom message of `no_na(message = "...")` applies when both
32//! are written.
33//!
34//! The marker composes with the precondition markers
35//! (`Unchecked<NonNa<Vec<f64>>>` drops the type checks and keeps this one).
36//! Like them it goes outermost (`NonNa<Option<T>>` is refused, since a value
37//! without `NA` makes `Option` mean only `NULL`: write `Option<T>` with
38//! `#[miniextendr(no_na)]` for that), it is a parameter type only, and it
39//! cannot appear in a `#[miniextendr]` trait's method signature (spell
40//! `no_na(x)` on the impl) or on an `extern "C-unwind"` function.
41//!
42//! # Construction
43//!
44//! The generated wrapper builds a `NonNa` after its check. Rust code builds
45//! one with [`NonNa::new`], which checks the value ([`MaybeNa`]) and returns
46//! `None` when it holds an `NA`, or with [`NonNa::new_unchecked`], whose
47//! caller promises there is none. There is no other way in: the field is
48//! private, and there is no `DerefMut` / `AsMut`, which would let code write
49//! an `NA` into it.
50
51use std::borrow::Borrow;
52use std::ops::Deref;
53
54use crate::sexp_types::{IsNA, RLogical, Rcomplex};
55
56/// A value that holds no R `NA`: a `#[miniextendr]` parameter refuses an
57/// argument with one (see the [module docs](self)). Transparent over `T`.
58#[repr(transparent)]
59#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
    NonNa<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "NonNa",
            &&self.0)
    }
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
    NonNa<T> {
    #[inline]
    fn clone(&self) -> Self { NonNa(::core::clone::Clone::clone(&self.0)) }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy> ::core::marker::Copy for
    NonNa<T> {
}Copy, #[automatically_derived]impl<T: ::core::cmp::PartialEq>
    ::core::marker::StructuralPartialEq for NonNa<T> {
}
#[automatically_derived]impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq
    for NonNa<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl<T: ::core::cmp::Eq> ::core::cmp::Eq for NonNa<T>
    {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) { let _: ::core::cmp::AssertParamIsEq<T>; }
}Eq, #[automatically_derived]impl<T: ::core::cmp::PartialOrd>
    ::core::cmp::PartialOrd for NonNa<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
    NonNa<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
    NonNa<T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash)]
60pub struct NonNa<T>(T);
61
62impl<T: MaybeNa> NonNa<T> {
63    /// `value` as a `NonNa`, or `None` when it holds an `NA`
64    /// ([`MaybeNa::has_na`]).
65    #[inline]
66    pub fn new(value: T) -> Option<Self> {
67        if value.has_na() {
68            None
69        } else {
70            Some(NonNa(value))
71        }
72    }
73}
74
75impl<T> NonNa<T> {
76    /// `value` as a `NonNa`, without checking it.
77    ///
78    /// # Safety
79    ///
80    /// `value` must hold no `NA` in the sense of `anyNA()`: code receiving a
81    /// `NonNa` relies on that.
82    #[inline]
83    pub const unsafe fn new_unchecked(value: T) -> Self {
84        NonNa(value)
85    }
86
87    /// The value.
88    #[inline]
89    pub fn into_inner(self) -> T {
90        self.0
91    }
92
93    /// The value; the same as [`into_inner`](Self::into_inner). It never
94    /// panics: a `NonNa` always holds one.
95    #[inline]
96    pub fn unwrap(self) -> T {
97        self.0
98    }
99}
100
101impl<T: Copy> NonNa<T> {
102    /// A copy of the value, as `NonZero::get` gives one.
103    #[inline]
104    pub fn get(self) -> T {
105        self.0
106    }
107}
108
109impl<T> Deref for NonNa<T> {
110    type Target = T;
111
112    #[inline]
113    fn deref(&self) -> &T {
114        &self.0
115    }
116}
117
118impl<T> AsRef<T> for NonNa<T> {
119    #[inline]
120    fn as_ref(&self) -> &T {
121        &self.0
122    }
123}
124
125impl<T> Borrow<T> for NonNa<T> {
126    #[inline]
127    fn borrow(&self) -> &T {
128        &self.0
129    }
130}
131
132/// A type whose values can hold R's `NA`, with the check [`NonNa::new`]
133/// makes.
134///
135/// [`has_na`](Self::has_na) counts what `anyNA()` counts: `NA_integer_`,
136/// `NA` logicals, `NaN` doubles and complex numbers (R's `NA_real_` is one),
137/// and `None`, which is how an `Option` element holds `NA`. A `String` never
138/// holds one: R's `NA_character_` has no `String` form.
139pub trait MaybeNa {
140    /// Whether the value holds an `NA`.
141    fn has_na(&self) -> bool;
142}
143
144impl MaybeNa for i32 {
145    #[inline]
146    fn has_na(&self) -> bool {
147        IsNA::is_na(self)
148    }
149}
150
151impl MaybeNa for RLogical {
152    #[inline]
153    fn has_na(&self) -> bool {
154        IsNA::is_na(self)
155    }
156}
157
158impl MaybeNa for f64 {
159    #[inline]
160    fn has_na(&self) -> bool {
161        self.is_nan()
162    }
163}
164
165impl MaybeNa for f32 {
166    #[inline]
167    fn has_na(&self) -> bool {
168        self.is_nan()
169    }
170}
171
172impl MaybeNa for Rcomplex {
173    #[inline]
174    fn has_na(&self) -> bool {
175        self.r.is_nan() || self.i.is_nan()
176    }
177}
178
179/// Types with no `NA` form: an R `NA` is refused when converting to them, or
180/// (strings) has no value of the type.
181macro_rules! never_na {
182    ($($ty:ty),* $(,)?) => {$(
183        impl MaybeNa for $ty {
184            #[inline]
185            fn has_na(&self) -> bool {
186                false
187            }
188        }
189    )*};
190}
191
192impl MaybeNa for bool {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for u8 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for i8 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for u16 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for i16 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for u32 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for i64 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for u64 {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for isize {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for usize {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for String {
    #[inline]
    fn has_na(&self) -> bool { false }
}
impl MaybeNa for str {
    #[inline]
    fn has_na(&self) -> bool { false }
}never_na!(
193    bool, u8, i8, u16, i16, u32, i64, u64, isize, usize, String, str
194);
195
196impl<T: MaybeNa> MaybeNa for Option<T> {
197    #[inline]
198    fn has_na(&self) -> bool {
199        self.as_ref().is_none_or(MaybeNa::has_na)
200    }
201}
202
203impl<T: MaybeNa> MaybeNa for [T] {
204    #[inline]
205    fn has_na(&self) -> bool {
206        self.iter().any(MaybeNa::has_na)
207    }
208}
209
210impl<T: MaybeNa, const N: usize> MaybeNa for [T; N] {
211    #[inline]
212    fn has_na(&self) -> bool {
213        self.as_slice().has_na()
214    }
215}
216
217impl<T: MaybeNa> MaybeNa for Vec<T> {
218    #[inline]
219    fn has_na(&self) -> bool {
220        self.as_slice().has_na()
221    }
222}
223
224impl<T: MaybeNa + ?Sized> MaybeNa for Box<T> {
225    #[inline]
226    fn has_na(&self) -> bool {
227        (**self).has_na()
228    }
229}
230
231impl<T: MaybeNa + ?Sized> MaybeNa for &T {
232    #[inline]
233    fn has_na(&self) -> bool {
234        (**self).has_na()
235    }
236}
237
238#[cfg(test)]
239mod tests;