diff --git a/_freeze/heckin-case-converter/execute-results/html.json b/_freeze/heckin-case-converter/execute-results/html.json new file mode 100644 index 0000000..ae0bf8c --- /dev/null +++ b/_freeze/heckin-case-converter/execute-results/html.json @@ -0,0 +1,15 @@ +{ + "hash": "e574f9355b2df3bb424c15083347d4a2", + "result": { + "engine": "knitr", + "markdown": "---\ntitle: \"A package from start to finish\"\nsubtitle: \"making a heckin' case converter\"\nfreeze: true\n---\n\n\nThe Rust crate ecosystem is rich with very small and very powerful utility libraries. One of the most downloaded crates is [heck](https://docs.rs/heck). It provides traits and structs to perform some of the most common case conversions.\n\nIn this tutorial we'll create a 0 dependency R package to provide the common case conversions. The resultant R package will be more performant but less flexible than the [`{snakecase}`](https://tazinho.github.io/snakecase/) R package. \n\nThis tutorial covers: \n\n- vectorization\n- `NA` handling\n- code generation using a macro\n\n## Getting started\n\nCreate a new R package:\n\n```r\nusethis::create_package(\"heck\")\n```\n\nWhen the new R package has opened up, add `extendr`.\n\n```r\nrextendr::use_extendr(crate_name = \"rheck\", lib_name = \"rheck\")\n```\n\n::: callout-note\nWhen adding the extendr dependency, make sure that the `crate_name` and `lib_name` arguments _are not_ `heck`. In order to add the `heck` crate as a dependency, the crate itself cannot be called `heck` because it creates a recursive dependency. Doing this allows us to name the R package `{heck}`, but the internal Rust crate is called `rheck`.\n:::\n\nNext, `heck` is needed as a dependency. From your terminal, navigate to `src/rust` and run `cargo add heck`. With this, you have everything you need to get started.\n\n\n## snek case conversion\n\n\n\n\n::: {.cell}\n\n```{.rust .cell-code}\nuse heck::ToSnekCase;\n```\n:::\n\n\nLet's start by creating a simple function to take a single string, and convert it to snake case. First, the trait `ToSnekCase` needs to be imported so that the method `to_snek_case()` is available to `&str`.\n\n\n::: {.cell}\n\n```{.rust .cell-code}\nuse heck::ToSnekCase;\n\n#[extendr]\nfn to_snek_case(x: &str) -> String {\n x.to_snek_case()\n}\n```\n:::\n\n\nSimple enough, right? Let's give it a shot. To make it accessible from your R session, it needs to be included in your `extendr_module! {}` macro. \n\n```rust\nextendr_module! {\n mod heck;\n fn to_snek_case;\n}\n```\n\nFrom your R session, run `rextendr::document()` followed by `devtools::load_all()` to make the function available. We'll skip these step from now on, but be sure to remember it!\n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_snek_case(\"MakeMe-Snake case\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"make_me_snake_case\"\n```\n\n\n:::\n:::\n\n\nRarely is it useful to run a function on just a scalar character value. Rust, though, works with scalars by default and adding vectorization is another step. \n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_snek_case(c(\"DontStep\", \"on-Snek\"))\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in to_snek_case(c(\"DontStep\", \"on-Snek\")): Not a string object.\n```\n\n\n:::\n:::\n\n\nProviding a character vector causes an error. So how do you go about vectorizing? \n\n## vectorizing snek case conversion\n\nTo vectorize this function, you need to be apply the conversion to each element in a character vector. The extendr wrapper struct for a character vector is called `Strings`. To take in a character vector and also return one, the function signature should look like this:\n\n```rust\n#[extendr]\nfn to_snek_case(x: Strings) -> Strings {\n}\n```\n\nThis says there is an argument `x` which must be a character vector and this function must also `->` return the `Strings` (a character vector).\n\nTo iterate through this you can use the `.into_iter()` method on the character vector. \n\n```rust\n#[extendr]\nfn to_snek_case(x: Strings) -> Strings {\n x\n .into_iter()\n // the rest of the function\n}\n```\n\nIterators have a method called `.map()` (yes, just like `purrr::map()`). It lets you apply a closure (an anonymous function) to each element of the iterator. In this case, each element is an [`Rstr`](https://extendr.github.io/extendr/extendr_api/wrapper/rstr/struct.Rstr.html). The `Rstr` has a method `.as_str()` which will return a string slice `&str`. You can take this slice and pass it on to `.to_snek_case()`. After having mapped over each element, the results are `.collect()`ed into another `Strings`. \n\n\n\n::: {.cell preamble='use_heck'}\n\n```{.rust .cell-code}\n#[extendr]\nfn to_snek_case(x: Strings) -> Strings {\n x\n .into_iter()\n .map(|xi| {\n xi.as_str().to_snek_case()\n })\n .collect::()\n}\n```\n:::\n\n\n\nThis new version of the function can be used in a vectorized manner: \n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_snek_case(c(\"DontStep\", \"on-Snek\"))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"dont_step\" \"on_snek\" \n```\n\n\n:::\n:::\n\n\nBut can it handle a missing value out of the box? \n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_snek_case(c(\"DontStep\", NA_character_, \"on-Snek\"))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"dont_step\" \"na\" \"on_snek\" \n```\n\n\n:::\n:::\n\n\nWell, sort of. The `as_str()` method when used on a missing value will return `\"NA\"` which is not in a user's best interest. \n\n\n## handling missing values\n\nInstead of returning `\"na\"`, it would be better to return an _actual_ missing value. Those can be created each scalar's `na()` method e.g. `Rstr::na()`. \n\nYou can modify the `.map()` statement to check if an `NA` is present, and, if so, return an `NA` value. To perform this check, use the `is_na()` method which returns a `bool` which is either `true` or `false`. The result can be [`match`ed](https://doc.rust-lang.org/book/ch06-02-match.html). When it is missing, the match arm returns the `NA` scalar value. When it is not missing, the `Rstr` is converted to snek case. However, since the `true` arm is an `Rstr` the other `false` arm must _also_ be an `Rstr`. To accomplish this use the `Rstr::from()` method. \n\n\n::: {.cell preamble='use_heck' profile='release'}\n\n```{.rust .cell-code}\n#[extendr]\nfn to_snek_case(x: Strings) -> Strings {\n x.into_iter()\n .map(|xi| match xi.is_na() {\n true => Rstr::na(),\n false => Rstr::from(xi.as_str().to_snek_case()),\n })\n .collect::()\n}\n```\n:::\n\n\nThis function can now handle missing values! \n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_snek_case(c(\"DontStep\", NA_character_, \"on-Snek\"))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"dont_step\" NA \"on_snek\" \n```\n\n\n:::\n:::\n\n\n## automating other methods with a macro! \n\nThere are traits for the other case conversions such as `ToKebabCase`, `ToPascalCase`, `ToShoutyKebabCase` and others. The each have a similar method name: `.to_kebab_case()`, `to_pascal_case()`, `.to_shouty_kebab_case()`. You can either choose to copy the above and change the method call multiple times, _or_ use a macro as a form of code generation. \n\nA macro allows you to generate code in a short hand manner. This macro take an identifier which has a placeholder called `$fn_name`: `$fn_name:ident`. \n\n```rust\nmacro_rules! make_heck_fn {\n ($fn_name:ident) => {\n #[extendr]\n /// @export\n fn $fn_name(x: Strings) -> Strings {\n x.into_iter()\n .map(|xi| match xi.is_na() {\n true => Rstr::na(),\n false => Rstr::from(xi.as_str().$fn_name()),\n })\n .collect::()\n }\n };\n}\n```\n\nThe `$fn_name` placeholder is put as the function name definition which is the same as the method name. To use this macro to generate the rest of the functions the other traits need to be imported.\n\n\n::: {.cell}\n\n```{.rust .cell-code}\nuse heck::{\n ToKebabCase, ToShoutyKebabCase,\n ToSnekCase, ToShoutySnakeCase,\n ToPascalCase, ToUpperCamelCase,\n ToTrainCase, ToTitleCase,\n};\n```\n:::\n\n\nWith the traits in scope, the macro can be invoked to generate the other functions.\n\n```rust\nmake_heck_fn!(to_snek_case);\nmake_heck_fn!(to_shouty_snake_case);\nmake_heck_fn!(to_kebab_case);\nmake_heck_fn!(to_shouty_kebab_case);\nmake_heck_fn!(to_pascal_case);\nmake_heck_fn!(to_upper_camel_case);\nmake_heck_fn!(to_train_case);\nmake_heck_fn!(to_title_case);\n```\n\nNote that each of these functions should be added to the `extendr_module! {}` macro in order for them to be available from R. \n\n\n\n\n\nTest it out with the `to_shouty_kebab_case()` function! \n\n\n::: {.cell}\n\n```{.r .cell-code}\nto_shouty_kebab_case(\"lorem:IpsumDolor__sit^amet\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"LOREM-IPSUM-DOLOR-SIT-AMET\"\n```\n\n\n:::\n:::\n\n\nAnd with that, you've created an R package that provides case conversion using heck and with very little code!\n\n\n## bench marking with `{snakecase}`\n\nTo illustrate the performance gains from using a vectorized Rust funciton, a `bench::mark()` is created between `to_snek_case()` and `snakecase::to_snake_case()`.\n\n\n\n\n\nThe bench mark will use 5000 randomly generated lorem ipsum sentences. \n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- unlist(lorem::ipsum(5000, 1, 25))\n\nhead(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"Consectetur montes fames netus odio dis nulla ut habitasse tristique diam ac arcu ante lacus in metus odio sociosqu mattis cras vitae dignissim quis ullamcorper urna dis.\" \n[2] \"Consectetur sapien platea inceptos orci aliquet turpis urna in suscipit bibendum class cubilia pretium tempus tempor eros duis etiam sapien viverra.\" \n[3] \"Adipiscing mi tortor vitae aenean condimentum magna varius risus netus viverra lobortis habitant nulla ornare sapien dapibus fermentum taciti porttitor luctus odio pharetra lacinia imperdiet a himenaeos.\"\n[4] \"Amet eleifend habitasse malesuada est commodo nulla nullam libero erat vivamus scelerisque curae tortor porta torquent fermentum eget morbi cursus urna consequat ridiculus velit per!\" \n[5] \"Elit felis est facilisi ante scelerisque nam per venenatis eu neque cum quisque odio mauris phasellus ante erat potenti ultricies vehicula fames mi nullam montes malesuada.\" \n[6] \"Consectetur metus neque egestas tellus vulputate porta primis sociosqu posuere congue facilisis sociosqu ad convallis cras ante dictumst felis libero taciti eu ridiculus sollicitudin nascetur!\" \n```\n\n\n:::\n\n```{.r .cell-code}\nbench::mark(\n rust = to_snek_case(x),\n snakecase = snakecase::to_snake_case(x)\n)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 2 × 6\n expression min median `itr/sec` mem_alloc `gc/sec`\n \n1 rust 15ms 16.3ms 61.1 1.16MB 0 \n2 snakecase 249ms 250.2ms 4.00 12.27MB 6.00\n```\n\n\n:::\n:::\n\n\n\n\n## The whole thing\n\nIn just 42 lines of code (empty lines included), you can create a very performant R package! \n\n```rust\nuse extendr_api::prelude::*;\n\nuse heck::{\n ToKebabCase, ToPascalCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnekCase, ToTitleCase,\n ToTrainCase, ToUpperCamelCase,\n};\n\nmacro_rules! make_heck_fn {\n ($fn_name:ident) => {\n #[extendr]\n /// @export\n fn $fn_name(x: Strings) -> Strings {\n x.into_iter()\n .map(|xi| match xi.is_na() {\n true => Rstr::na(),\n false => Rstr::from(xi.as_str().$fn_name()),\n })\n .collect::()\n }\n };\n}\n\nmake_heck_fn!(to_snek_case);\nmake_heck_fn!(to_shouty_snake_case);\nmake_heck_fn!(to_kebab_case);\nmake_heck_fn!(to_shouty_kebab_case);\nmake_heck_fn!(to_pascal_case);\nmake_heck_fn!(to_upper_camel_case);\nmake_heck_fn!(to_train_case);\nmake_heck_fn!(to_title_case);\n\nextendr_module! {\n mod heck;\n fn to_snek_case;\n fn to_shouty_snake_case;\n fn to_kebab_case;\n fn to_shouty_kebab_case;\n fn to_pascal_case;\n fn to_upper_camel_case;\n fn to_title_case;\n fn to_train_case;\n}\n```", + "supporting": [], + "filters": [ + "rmarkdown/pagebreak.lua" + ], + "includes": {}, + "engineDependencies": {}, + "preserve": {}, + "postProcess": true + } +} \ No newline at end of file diff --git a/_freeze/using-rust-types/execute-results/html.json b/_freeze/using-rust-types/execute-results/html.json new file mode 100644 index 0000000..a0ccd6e --- /dev/null +++ b/_freeze/using-rust-types/execute-results/html.json @@ -0,0 +1,15 @@ +{ + "hash": "9dd6283ce00c18d60af0d60a38b06781", + "result": { + "engine": "knitr", + "markdown": "---\ntitle: \"Using Rust types in R\"\nfreeze: true\n---\n\n::: {.cell}\n\n:::\n\n\nThis tutorial demonstrates some of the basics of passing data types back and\nforth between Rust and R. This includes all of the following:\n\n- Passing scalar types between R and Rust.\n- Passing vector types between R and Rust.\n- Printing from Rust to the console in R.\n- Handling missing values in Rust (a primer).\n\nWe'll start with examples showing how to pass R types as explicit Rust types.\nThis is useful for demonstration purposes, but it does ignore one very very big\nissue, and that's missing values. Rust data types do not allow for missing\nvalues, so they have to be handled carefully. Fortunately, extendr offers its\nown data types built on top of the Rust types to do that for you. For this\nreason, **it is strongly recommended that you work with the extendr types\nwherever possible.** However, when first getting comfortable with extendr, \nand possible even Rust, it may feel more comfortable to work with Rust\nnative types. \n\n## Scalar Type Mapping with Rust Types\n\nIn R, there is no such thing as a scalar value. Everything is a vector.\nWhen using a scalar value in R, that is really a length one vector. In Rust,\nhowever, scalar values are the building blocks of everything. \n\nBelow is a mapping of scalar values between R, extendr, and Rust. \n\n\n| R type | extendr type | Rust type |\n|----------------|--------------|----------------|\n| `integer(1)` | `Rint` | `i32` |\n| `double(1)` | `Rfloat` | `f64` |\n| `logical(1)` | `Rbool` | `bool` |\n| `complex(1)` | `Rcplx` | `Complex` |\n| `character(1)` | `Rstr` | `String` |\n\nTo see how these scalars get passed back and forth between Rust and R,\nwe'll first explore Rust's `f64` value which is a 64-bit float. This is \nequivalent to R's `double(1)`. We'll write a very simple Rust function that \nprints the value of the input and does not return anything. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn scalar_double(x: f64) { \n rprintln!(\"The value of x is {x}\"); \n}\n```\n:::\n\n\n::: callout-note\nNote the use of `rprintln!()` instead of the `println!()` macro.\nUsing `println!()` will not always be captured by the R console. Using\n`rprintln!()` will ensure that it is. \n:::\n\nIf you are not working inside of an extendr R package, you can create this function locally\nusing `rextendr::rust_function()`.\n\n```r\nrextendr::rust_function(\"\nfn scalar_double(x: f64) { \n rprintln!(\"The value of x is {x}\"); \n}\n\")\n```\n\nTry calling this function on a single double value. \n\n\n::: {.cell}\n\n```{.r .cell-code}\nscalar_double(4.2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nThe value of x is 4.2\n```\n\n\n:::\n:::\n\n\nA couple of things to note with this example. First, `x: f64` tells Rust that\nthe type of `x` being passed to the function is a single double vector or \"float\"\nvalue. Second, `rprintln!(\"{}\", x);` is an extendr macro (the give-away for this\nis the `!`) that makes it easier to print information from Rust to the console\nin R. R users will perhaps notice that the syntax is vaguely `{glue}`-like in\nthat the value of x is inserted into the curly brackets.\n\nNow, what if, rather than printing the value of `x` to the R console, we wanted\ninstead to return that value to R? To do that, we just need to let Rust know\nwhat type is being returned by our function. This is done with the `-> type`\nnotation. The extendr crate knows how to handle the scalar `f64` type and pass\nit to R as double.\n\n\n::: {.cell}\n\n```{.rust .cell-code}\nfn scalar_double(x: f64) -> f64 { \n x \n}\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- scalar_double(4.2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nThe value of x is 4.2\n```\n\n\n:::\n\n```{.r .cell-code}\ntypeof(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"NULL\"\n```\n\n\n:::\n\n```{.r .cell-code}\nx + 1\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nnumeric(0)\n```\n\n\n:::\n:::\n\n\n### Additional examples\n\nWe can extend this example to `i32`, `bool` and `String` values in Rust. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn scalar_integer(x: i32) -> i32 { x }\n\n#[extendr]\nfn scalar_logical(x: bool) -> bool { x }\n\n#[extendr]\nfn scalar_character(x: String) -> String { x }\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nscalar_integer(4L)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 4\n```\n\n\n:::\n\n```{.r .cell-code}\nscalar_logical(TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nscalar_character(\"Hello world!\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"Hello world!\"\n```\n\n\n:::\n:::\n\n\n## Vector Type Mapping with Rust Types\n\nWhat happens if we try to pass more than one value to `scalar_double()`?\n\n\n::: {.cell}\n\n```{.r .cell-code}\nscalar_double(c(4.2, 1.3, 2.5))\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in scalar_double(c(4.2, 1.3, 2.5)): Input must be of length 1. Vector of length >1 given.\n```\n\n\n:::\n:::\n\n\nIt errors because the function expects a scalar of the `f64` type, not a vector\nof `f64`. \n\nIn this section, we show you how to pass Rust vectors between R and Rust.\n\n::: callout-important\nWhile using a Rust vector is possible in some cases, it is strongly\nnot recommended. Instead, extendr types should be used as they provide\naccess directly to R objectes. Whereas using Rust vectors requires \nadditional allocations. \n:::\n\n\nThe syntax is basically the same as with scalars, with just some minor changes.\nWe'll use doubles again to demonstrate this.\n\nFor reference, below are the type of Rust vectors that can be utilized with extendr.\n\n| R type | extendr type | Rust type |\n|---------------|--------------|---------------------|\n| `integer()` | `Integers` | `Vec` |\n| `double()` | `Doubles` | `Vec` |\n| `complex()` | `Complexes` | `Vec>` |\n| `character()` | `Strings` | `Vec` |\n| `raw()` | `Raw` | `&[u8]` |\n| `logical()` | `Logicals` | |\n| `list()` | `List` | |\n\n::: callout-note\nYou might have anticipated `Vec` to be a supported Rust \nvector type. This is not possible because in R, logical vectors\ndo not contain _only_ `true` and `false` like Rust's bool type. \nThey also can be an `NA` value which has no corresponding representation\nin Rust. \n:::\n\n\nBelow defines Rust function which takes in a vector of `f64` values and prints them out. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn vector_double(x: Vec) {\n rprintln!(\"The values of x are {x:?}\");\n}\n```\n:::\n\n\nThat function can be called from R which prints the Debug format of the vector. \n\n::: callout-tip\nRust's vector do not implement the [Display](https://doc.rust-lang.org/std/fmt/trait.Display.html) trait so the debug format (`:?`) is used.\n:::\n\n\n::: {.cell}\n\n```{.r .cell-code}\nvector_double(c(4.2, 1.3, 2.5))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nThe values of x are [4.2, 1.3, 2.5]\n```\n\n\n:::\n:::\n\n\n\nReturning 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 `;`. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn vector_double(x: Vec) -> Vec { \n x \n}\n```\n:::\n\n\nCalling the function returns the input as a double vector\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- vector_double(c(4.2, 1.3, 2.5))\ntypeof(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"double\"\n```\n\n\n:::\n\n```{.r .cell-code}\nx + 1\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 5.2 2.3 3.5\n```\n\n\n:::\n:::\n\n\n### Additional examples\n\nThese same principles can be extended to other supported vector types such as `Vec` and `Vec`.\n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn vector_integer(x: Vec) -> Vec { \n x\n}\n\n#[extendr]\nfn vector_character(x: Vec) -> Vec {\n x \n}\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nvector_integer(c(4L, 6L, 8L))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 4 6 8\n```\n\n\n:::\n\n```{.r .cell-code}\nvector_character(c(\"Hello world!\", \"Hello extendr!\", \"Hello R!\"))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"Hello world!\" \"Hello extendr!\" \"Hello R!\" \n```\n\n\n:::\n:::\n\n\n## Missing values\n\nIn 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. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr]\nfn plus_one(x: f64) -> f64 { \n x + 1.0 \n}\n```\n:::\n\n\nRunning this using a missing value results in an error. \n\n\n::: {.cell}\n\n```{.r .cell-code}\nplus_one(NA_real_)\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in plus_one(NA_real_): Input must not be NA.\n```\n\n\n:::\n:::\n\n\nThese 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\n`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. \n\n\n::: {.cell}\n\n```{.rust .cell-code}\n#[extendr(use_try_from = true)]\nfn plus_one(x: Rfloat) -> Rfloat { \n x + 1.0 \n}\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nplus_one(NA_real_)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] NA\n```\n\n\n:::\n\n```{.r .cell-code}\nplus_one(4.2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 5.2\n```\n\n\n:::\n:::\n\n\nThe combination of these two changes allows us to pass missing values to our `plus_one()` function and return\nmissing values without raising an error.\n", + "supporting": [], + "filters": [ + "rmarkdown/pagebreak.lua" + ], + "includes": {}, + "engineDependencies": {}, + "preserve": {}, + "postProcess": true + } +} \ No newline at end of file diff --git a/_quarto.yml b/_quarto.yml index 3ca947f..ee0c149 100644 --- a/_quarto.yml +++ b/_quarto.yml @@ -20,6 +20,7 @@ website: - data-types.qmd - extendr-macro.qmd - conversion.qmd + - heckin-case-converter.qmd style: "docked" search: true navbar: diff --git a/heckin-case-converter.qmd b/heckin-case-converter.qmd new file mode 100644 index 0000000..13e16c8 --- /dev/null +++ b/heckin-case-converter.qmd @@ -0,0 +1,313 @@ +--- +title: "A package from start to finish" +subtitle: "making a heckin' case converter" +freeze: true +--- + +The Rust crate ecosystem is rich with very small and very powerful utility libraries. One of the most downloaded crates is [heck](https://docs.rs/heck). It provides traits and structs to perform some of the most common case conversions. + +In this tutorial we'll create a 0 dependency R package to provide the common case conversions. The resultant R package will be more performant but less flexible than the [`{snakecase}`](https://tazinho.github.io/snakecase/) R package. + +This tutorial covers: + +- vectorization +- `NA` handling +- code generation using a macro + +## Getting started + +Create a new R package: + +```r +usethis::create_package("heck") +``` + +When the new R package has opened up, add `extendr`. + +```r +rextendr::use_extendr(crate_name = "rheck", lib_name = "rheck") +``` + +::: callout-note +When adding the extendr dependency, make sure that the `crate_name` and `lib_name` arguments _are not_ `heck`. In order to add the `heck` crate as a dependency, the crate itself cannot be called `heck` because it creates a recursive dependency. Doing this allows us to name the R package `{heck}`, but the internal Rust crate is called `rheck`. +::: + +Next, `heck` is needed as a dependency. From your terminal, navigate to `src/rust` and run `cargo add heck`. With this, you have everything you need to get started. + + +## snek case conversion + +```{r, include = FALSE} +library(rextendr) +knitr::opts_chunk$set(engine.opts = list(dependencies = list(heck = "0.5.0"))) +``` + +```{extendrsrc use_heck} +use heck::ToSnekCase; +``` + +Let's start by creating a simple function to take a single string, and convert it to snake case. First, the trait `ToSnekCase` needs to be imported so that the method `to_snek_case()` is available to `&str`. + +```{extendrsrc} +use heck::ToSnekCase; + +#[extendr] +fn to_snek_case(x: &str) -> String { + x.to_snek_case() +} +``` + +Simple enough, right? Let's give it a shot. To make it accessible from your R session, it needs to be included in your `extendr_module! {}` macro. + +```rust +extendr_module! { + mod heck; + fn to_snek_case; +} +``` + +From your R session, run `rextendr::document()` followed by `devtools::load_all()` to make the function available. We'll skip these step from now on, but be sure to remember it! + +```{r} +to_snek_case("MakeMe-Snake case") +``` + +Rarely is it useful to run a function on just a scalar character value. Rust, though, works with scalars by default and adding vectorization is another step. + +```{r, error = TRUE} +to_snek_case(c("DontStep", "on-Snek")) +``` + +Providing a character vector causes an error. So how do you go about vectorizing? + +## vectorizing snek case conversion + +To vectorize this function, you need to be apply the conversion to each element in a character vector. The extendr wrapper struct for a character vector is called `Strings`. To take in a character vector and also return one, the function signature should look like this: + +```rust +#[extendr] +fn to_snek_case(x: Strings) -> Strings { +} +``` + +This says there is an argument `x` which must be a character vector and this function must also `->` return the `Strings` (a character vector). + +To iterate through this you can use the `.into_iter()` method on the character vector. + +```rust +#[extendr] +fn to_snek_case(x: Strings) -> Strings { + x + .into_iter() + // the rest of the function +} +``` + +Iterators have a method called `.map()` (yes, just like `purrr::map()`). It lets you apply a closure (an anonymous function) to each element of the iterator. In this case, each element is an [`Rstr`](https://extendr.github.io/extendr/extendr_api/wrapper/rstr/struct.Rstr.html). The `Rstr` has a method `.as_str()` which will return a string slice `&str`. You can take this slice and pass it on to `.to_snek_case()`. After having mapped over each element, the results are `.collect()`ed into another `Strings`. + + +```{extendrsrc preamble = "use_heck"} +#[extendr] +fn to_snek_case(x: Strings) -> Strings { + x + .into_iter() + .map(|xi| { + xi.as_str().to_snek_case() + }) + .collect::() +} +``` + + +This new version of the function can be used in a vectorized manner: + +```{r} +to_snek_case(c("DontStep", "on-Snek")) +``` + +But can it handle a missing value out of the box? + +```{r} +to_snek_case(c("DontStep", NA_character_, "on-Snek")) +``` + +Well, sort of. The `as_str()` method when used on a missing value will return `"NA"` which is not in a user's best interest. + + +## handling missing values + +Instead of returning `"na"`, it would be better to return an _actual_ missing value. Those can be created each scalar's `na()` method e.g. `Rstr::na()`. + +You can modify the `.map()` statement to check if an `NA` is present, and, if so, return an `NA` value. To perform this check, use the `is_na()` method which returns a `bool` which is either `true` or `false`. The result can be [`match`ed](https://doc.rust-lang.org/book/ch06-02-match.html). When it is missing, the match arm returns the `NA` scalar value. When it is not missing, the `Rstr` is converted to snek case. However, since the `true` arm is an `Rstr` the other `false` arm must _also_ be an `Rstr`. To accomplish this use the `Rstr::from()` method. + +```{extendrsrc preamble = "use_heck", profile="release"} +#[extendr] +fn to_snek_case(x: Strings) -> Strings { + x.into_iter() + .map(|xi| match xi.is_na() { + true => Rstr::na(), + false => Rstr::from(xi.as_str().to_snek_case()), + }) + .collect::() +} +``` + +This function can now handle missing values! + +```{r} +to_snek_case(c("DontStep", NA_character_, "on-Snek")) +``` + +## automating other methods with a macro! + +There are traits for the other case conversions such as `ToKebabCase`, `ToPascalCase`, `ToShoutyKebabCase` and others. The each have a similar method name: `.to_kebab_case()`, `to_pascal_case()`, `.to_shouty_kebab_case()`. You can either choose to copy the above and change the method call multiple times, _or_ use a macro as a form of code generation. + +A macro allows you to generate code in a short hand manner. This macro take an identifier which has a placeholder called `$fn_name`: `$fn_name:ident`. + +```rust +macro_rules! make_heck_fn { + ($fn_name:ident) => { + #[extendr] + /// @export + fn $fn_name(x: Strings) -> Strings { + x.into_iter() + .map(|xi| match xi.is_na() { + true => Rstr::na(), + false => Rstr::from(xi.as_str().$fn_name()), + }) + .collect::() + } + }; +} +``` + +The `$fn_name` placeholder is put as the function name definition which is the same as the method name. To use this macro to generate the rest of the functions the other traits need to be imported. + +```{extendrsrc heck_traits} +use heck::{ + ToKebabCase, ToShoutyKebabCase, + ToSnekCase, ToShoutySnakeCase, + ToPascalCase, ToUpperCamelCase, + ToTrainCase, ToTitleCase, +}; +``` + +With the traits in scope, the macro can be invoked to generate the other functions. + +```rust +make_heck_fn!(to_snek_case); +make_heck_fn!(to_shouty_snake_case); +make_heck_fn!(to_kebab_case); +make_heck_fn!(to_shouty_kebab_case); +make_heck_fn!(to_pascal_case); +make_heck_fn!(to_upper_camel_case); +make_heck_fn!(to_train_case); +make_heck_fn!(to_title_case); +``` + +Note that each of these functions should be added to the `extendr_module! {}` macro in order for them to be available from R. + +```{extendrsrc preamble = "heck_traits", include = FALSE} +#[extendr] +fn to_shouty_kebab_case(x: Strings) -> Strings { + x.into_iter() + .map(|xi| match xi.is_na() { + true => Rstr::na(), + false => Rstr::from(xi.as_str().to_shouty_kebab_case()), + }) + .collect::() +} +``` + +Test it out with the `to_shouty_kebab_case()` function! + +```{r} +to_shouty_kebab_case("lorem:IpsumDolor__sit^amet") +``` + +And with that, you've created an R package that provides case conversion using heck and with very little code! + + +## bench marking with `{snakecase}` + +To illustrate the performance gains from using a vectorized Rust funciton, a `bench::mark()` is created between `to_snek_case()` and `snakecase::to_snake_case()`. + +```{r include=FALSE} +rextendr::rust_source(code = r"( +use heck::ToSnekCase; + +#[extendr] +fn to_snek_case(x: Strings) -> Strings { + x.into_iter() + .map(|xi| match xi.is_na() { + true => Rstr::na(), + false => Rstr::from(xi.as_str().to_snek_case()), + }) + .collect::() +} +)", dependencies = list("heck" = "*"), profile = "release") +``` + +The bench mark will use 5000 randomly generated lorem ipsum sentences. + +```{r, warning = FALSE} +x <- unlist(lorem::ipsum(5000, 1, 25)) + +head(x) + +bench::mark( + rust = to_snek_case(x), + snakecase = snakecase::to_snake_case(x) +) +``` + + + +## The whole thing + +In just 42 lines of code (empty lines included), you can create a very performant R package! + +```rust +use extendr_api::prelude::*; + +use heck::{ + ToKebabCase, ToPascalCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnekCase, ToTitleCase, + ToTrainCase, ToUpperCamelCase, +}; + +macro_rules! make_heck_fn { + ($fn_name:ident) => { + #[extendr] + /// @export + fn $fn_name(x: Strings) -> Strings { + x.into_iter() + .map(|xi| match xi.is_na() { + true => Rstr::na(), + false => Rstr::from(xi.as_str().$fn_name()), + }) + .collect::() + } + }; +} + +make_heck_fn!(to_snek_case); +make_heck_fn!(to_shouty_snake_case); +make_heck_fn!(to_kebab_case); +make_heck_fn!(to_shouty_kebab_case); +make_heck_fn!(to_pascal_case); +make_heck_fn!(to_upper_camel_case); +make_heck_fn!(to_train_case); +make_heck_fn!(to_title_case); + +extendr_module! { + mod heck; + fn to_snek_case; + fn to_shouty_snake_case; + fn to_kebab_case; + fn to_shouty_kebab_case; + fn to_pascal_case; + fn to_upper_camel_case; + fn to_title_case; + fn to_train_case; +} +``` \ No newline at end of file