Skip to main content

filthy_rich/
macros.rs

1//! Public, crate-only macros.
2//!
3
4/// Generates a function `$name` which takes a `$param` and sets the
5/// `$name` field of a struct to be a `None`-filtered `String`.
6#[macro_export]
7macro_rules! nf {
8    ($name:ident, $doc:expr, $param:ident) => {
9        #[must_use]
10        #[doc = $doc]
11        pub fn $name(mut self, $param: impl Into<String>) -> Self {
12            let text = $param.into();
13            self.$name = (!text.is_empty()).then_some(text);
14            self
15        }
16    };
17}
18
19/// Generates a function which returns a borrowed `&str` for a given `String` field
20/// named `$name` in a class.
21#[macro_export]
22macro_rules! str {
23    ($name:ident, $doc:expr) => {
24        #[must_use]
25        #[doc = $doc]
26        pub fn $name(&self) -> &str {
27            &self.$name
28        }
29    };
30}
31
32/// Generates a function `$name` which returns an `Option<&str>` by
33/// dereferencing the `$name` field of a struct.
34#[macro_export]
35macro_rules! ds {
36    ($name:ident, $doc:expr) => {
37        #[must_use]
38        #[doc = $doc]
39        pub fn $name(&self) -> Option<&str> {
40            self.$name.as_deref()
41        }
42    };
43}