miniextendr_api/dataframe/borrowed.rs
1//! Borrowed rows → R `data.frame`: `IntoDataFrame` for `&[Row]` and `&Vec<Row>`.
2//!
3//! `#[derive(DataFrameRow)]` implements [`DataFrameRowBorrow`] on the row type
4//! next to [`DataFrameRowConvert`](super::DataFrameRowConvert). The generated
5//! fill walks the borrowed rows once into locals that have the companion's own
6//! column types, then runs the same column assembly code as the owned
7//! conversion, so both produce the same frame. `String` and `Option<String>`
8//! columns are written from `&str` (no `String` is cloned); every other value
9//! is cloned once into its column.
10
11use super::{BuiltDataFrame, DataFrame, DataFrameError, IntoDataFrame};
12use crate::SexpExt as _;
13use crate::list::List;
14
15// region: DataFrameRowBorrow — the derive's borrowed fill
16
17/// Borrowed rows → `data.frame` column list, emitted by `#[derive(DataFrameRow)]`
18/// on the **row type**.
19///
20/// The same orphan-rule bridge as [`DataFrameRowConvert`](super::DataFrameRowConvert):
21/// the derive implements this `#[doc(hidden)]` trait on the local row type, and
22/// `miniextendr_api` carries the blanket [`IntoDataFrame`] impls for `&[T]` and
23/// `&Vec<T>` below. Users call `rows.as_slice().into_dataframe()?` or
24/// `(&rows).into_dataframe()?`.
25///
26/// The derive implements it only where the fill can run: every value the fill
27/// clones has a `Clone` type, each bound behind a higher-ranked binder so the
28/// impl simply does not apply when one fails. A row with a non-`Clone` field
29/// therefore still derives, and converts as an owned `Vec<Row>`; asking for
30/// its borrowed conversion names the field type that is not `Clone`. The
31/// message below is for a row type that does not derive `DataFrameRow`.
32#[doc(hidden)]
33#[diagnostic::on_unimplemented(
34 message = "`{Self}` is not a `#[derive(DataFrameRow)]` row, so borrowed rows of it \
35 have no data.frame conversion",
36 label = "`&[{Self}]` / `&Vec<{Self}>` convert only for `DataFrameRow` rows",
37 note = "derive `DataFrameRow` on `{Self}`"
38)]
39pub trait DataFrameRowBorrow: Sized {
40 /// Build the `data.frame`-shaped column list of `rows` without consuming them.
41 fn rows_ref_into_column_list(rows: &[Self]) -> List;
42}
43
44/// Root a freshly assembled column list as a [`BuiltDataFrame`], refusing the
45/// unclassed list the column engine returns for unnamed columns.
46fn adopt_column_list(list: List) -> Result<BuiltDataFrame, DataFrameError> {
47 let sexp = list.as_sexp();
48 if !sexp.is_data_frame() {
49 return Err(DataFrameError::UnnamedColumns);
50 }
51 // SAFETY: the column engine built `sexp` on the R main thread just now and
52 // nothing allocated since; `adopt` roots it before anything else runs.
53 Ok(unsafe { BuiltDataFrame::adopt(DataFrame::from_built_sexp(sexp)) })
54}
55
56/// Borrowed rows → R `data.frame`, for a `#[derive(DataFrameRow)]` row type.
57///
58/// Builds the same frame as the owned `rows.to_vec().into_dataframe()` without
59/// the intermediate `Vec<Row>`: `String` and `Option<String>` columns are
60/// written straight from `&str`, and every other value is cloned once into its
61/// column (so those field types need `Clone`; the row type does not).
62///
63/// From a `&self` method, borrow the rows explicitly:
64/// `self.rows.as_slice().into_dataframe()` or `(&self.rows).into_dataframe()`.
65/// A bare `self.rows.into_dataframe()` resolves to the owned `Vec<Row>` impl
66/// and cannot move out of `&self`.
67///
68/// `into_dataframe_par` (`feature = "rayon"`) on borrowed rows is the same
69/// sequential fill.
70impl<T: DataFrameRowBorrow> IntoDataFrame for &[T] {
71 fn into_dataframe(self) -> Result<BuiltDataFrame, DataFrameError> {
72 adopt_column_list(T::rows_ref_into_column_list(self))
73 }
74}
75
76/// `&Vec<Row>` converts exactly as the borrowed slice `&[Row]` does.
77///
78/// This impl is what makes `(&self.rows).into_dataframe()` work: without it,
79/// method lookup would dereference to the owned `Vec<Row>` impl. Where this
80/// impl does not apply (a field type that is not `Clone`), lookup still falls
81/// through to that owned impl, so the error is "cannot move out of a shared
82/// reference" (E0507). `self.rows.as_slice().into_dataframe()` or
83/// `IntoDataFrame::into_dataframe(&self.rows)` names the field type instead.
84impl<T: DataFrameRowBorrow> IntoDataFrame for &Vec<T> {
85 fn into_dataframe(self) -> Result<BuiltDataFrame, DataFrameError> {
86 self.as_slice().into_dataframe()
87 }
88}
89// endregion
90
91// region: StringColumn — the by-reference string columns
92
93/// A `String` column the borrowed fill writes from `&str`.
94///
95/// Implemented only for `std::string::String`. The derive recognises a
96/// `String` column by name and bounds the borrowed impl on this trait, so a
97/// user type that happens to be called `String` never takes the `&str` path
98/// (its borrowed impl does not apply instead).
99#[doc(hidden)]
100pub trait StringColumn {
101 /// The string a column cell is written from.
102 fn __mx_column_str(&self) -> &str;
103}
104
105impl StringColumn for String {
106 #[inline(always)]
107 fn __mx_column_str(&self) -> &str {
108 self.as_str()
109 }
110}
111// endregion