This repository has been archived by the owner on Jun 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusing-rust-types.qmd
280 lines (203 loc) · 7.68 KB
/
using-rust-types.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
---
title: "Using Rust types in R"
freeze: true
---
```{r}
#| echo: false
library(rextendr)
```
This tutorial demonstrates some of the basics of passing data types back and
forth between Rust and R. This includes all of the following:
- Passing scalar types between R and Rust.
- Passing vector types between R and Rust.
- Printing from Rust to the console in R.
- Handling missing values in Rust (a primer).
We'll start with examples showing how to pass R types as explicit Rust types.
This is useful for demonstration purposes, but it does ignore one very very big
issue, and that's missing values. Rust data types do not allow for missing
values, so they have to be handled carefully. Fortunately, extendr offers its
own data types built on top of the Rust types to do that for you. For this
reason, **it is strongly recommended that you work with the extendr types
wherever possible.** However, when first getting comfortable with extendr,
and possible even Rust, it may feel more comfortable to work with Rust
native types.
## Scalar Type Mapping with Rust Types
In R, there is no such thing as a scalar value. Everything is a vector.
When using a scalar value in R, that is really a length one vector. In Rust,
however, scalar values are the building blocks of everything.
Below is a mapping of scalar values between R, extendr, and Rust.
| R type | extendr type | Rust type |
|----------------|--------------|----------------|
| `integer(1)` | `Rint` | `i32` |
| `double(1)` | `Rfloat` | `f64` |
| `logical(1)` | `Rbool` | `bool` |
| `complex(1)` | `Rcplx` | `Complex<f64>` |
| `character(1)` | `Rstr` | `String` |
To see how these scalars get passed back and forth between Rust and R,
we'll first explore Rust's `f64` value which is a 64-bit float. This is
equivalent to R's `double(1)`. We'll write a very simple Rust function that
prints the value of the input and does not return anything.
```{extendrsrc}
#[extendr]
fn scalar_double(x: f64) {
rprintln!("The value of x is {x}");
}
```
::: callout-note
Note the use of `rprintln!()` instead of the `println!()` macro.
Using `println!()` will not always be captured by the R console. Using
`rprintln!()` will ensure that it is.
:::
If you are not working inside of an extendr R package, you can create this function locally
using `rextendr::rust_function()`.
```r
rextendr::rust_function("
fn scalar_double(x: f64) {
rprintln!("The value of x is {x}");
}
")
```
Try calling this function on a single double value.
```{r}
scalar_double(4.2)
```
A couple of things to note with this example. First, `x: f64` tells Rust that
the type of `x` being passed to the function is a single double vector or "float"
value. Second, `rprintln!("{}", x);` is an extendr macro (the give-away for this
is the `!`) that makes it easier to print information from Rust to the console
in R. R users will perhaps notice that the syntax is vaguely `{glue}`-like in
that the value of x is inserted into the curly brackets.
Now, what if, rather than printing the value of `x` to the R console, we wanted
instead to return that value to R? To do that, we just need to let Rust know
what type is being returned by our function. This is done with the `-> type`
notation. The extendr crate knows how to handle the scalar `f64` type and pass
it to R as double.
```{extendrsrc}
fn scalar_double(x: f64) -> f64 {
x
}
```
```{r}
x <- scalar_double(4.2)
typeof(x)
x + 1
```
### Additional examples
We can extend this example to `i32`, `bool` and `String` values in Rust.
```{extendrsrc}
#[extendr]
fn scalar_integer(x: i32) -> i32 { x }
#[extendr]
fn scalar_logical(x: bool) -> bool { x }
#[extendr]
fn scalar_character(x: String) -> String { x }
```
```{r}
scalar_integer(4L)
scalar_logical(TRUE)
scalar_character("Hello world!")
```
## Vector Type Mapping with Rust Types
What happens if we try to pass more than one value to `scalar_double()`?
```{r}
#| error: true
scalar_double(c(4.2, 1.3, 2.5))
```
It errors because the function expects a scalar of the `f64` type, not a vector
of `f64`.
In this section, we show you how to pass Rust vectors between R and Rust.
::: callout-important
While using a Rust vector is possible in some cases, it is strongly
not recommended. Instead, extendr types should be used as they provide
access directly to R objectes. Whereas using Rust vectors requires
additional allocations.
:::
The syntax is basically the same as with scalars, with just some minor changes.
We'll use doubles again to demonstrate this.
For reference, below are the type of Rust vectors that can be utilized with extendr.
| R type | extendr type | Rust type |
|---------------|--------------|---------------------|
| `integer()` | `Integers` | `Vec<i32>` |
| `double()` | `Doubles` | `Vec<f64>` |
| `complex()` | `Complexes` | `Vec<Complex<f64>>` |
| `character()` | `Strings` | `Vec<String>` |
| `raw()` | `Raw` | `&[u8]` |
| `logical()` | `Logicals` | |
| `list()` | `List` | |
::: callout-note
You might have anticipated `Vec<bool>` to be a supported Rust
vector type. This is not possible because in R, logical vectors
do not contain _only_ `true` and `false` like Rust's bool type.
They also can be an `NA` value which has no corresponding representation
in Rust.
:::
Below defines Rust function which takes in a vector of `f64` values and prints them out.
```{extendrsrc}
#[extendr]
fn vector_double(x: Vec<f64>) {
rprintln!("The values of x are {x:?}");
}
```
That function can be called from R which prints the Debug format of the vector.
::: callout-tip
Rust's vector do not implement the [Display](https://doc.rust-lang.org/std/fmt/trait.Display.html) trait so the debug format (`:?`) is used.
:::
```{r}
vector_double(c(4.2, 1.3, 2.5))
```
Returning values using Rust follows the same rules as R. You do not need to explicitly return a value as long as the last item in an expression is not followed by a `;`.
```{extendrsrc}
#[extendr]
fn vector_double(x: Vec<f64>) -> Vec<f64> {
x
}
```
Calling the function returns the input as a double vector
```{r}
x <- vector_double(c(4.2, 1.3, 2.5))
typeof(x)
x + 1
```
### Additional examples
These same principles can be extended to other supported vector types such as `Vec<i32>` and `Vec<String>`.
```{extendrsrc}
#[extendr]
fn vector_integer(x: Vec<i32>) -> Vec<i32> {
x
}
#[extendr]
fn vector_character(x: Vec<String>) -> Vec<String> {
x
}
```
```{r}
vector_integer(c(4L, 6L, 8L))
vector_character(c("Hello world!", "Hello extendr!", "Hello R!"))
```
## Missing values
In Rust, missing values do not exist this in part why using Rust types alone is insufficient. Below a simple function which adds 1 to the input is defined.
```{extendrsrc}
#[extendr]
fn plus_one(x: f64) -> f64 {
x + 1.0
}
```
Running this using a missing value results in an error.
```{r}
#| error: true
plus_one(NA_real_)
```
These extendr types, however, can be utilized much like a normal `f64` that is `NA` aware. You will see that we have replaced the Rust type
`f64` with the extendr type `Rfloat`. Since `Rfloat` maps to a scalar value and not vector, the conversion needs to be handled more delicately. The macro was invoked with the `use_try_from = true` argument. This will eventually become the default behavior of extendr.
```{extendrsrc}
#[extendr(use_try_from = true)]
fn plus_one(x: Rfloat) -> Rfloat {
x + 1.0
}
```
```{r}
plus_one(NA_real_)
plus_one(4.2)
```
The combination of these two changes allows us to pass missing values to our `plus_one()` function and return
missing values without raising an error.