Skip to main content

argmin/core/
macros.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! # Macros
9
10/// Creates an `KV` at compile time
11///
12/// # Example
13///
14/// ```
15/// use argmin::kv;
16///
17/// let kv = kv!(
18///     "key1" => "value1";
19///     "key2" => "value2";
20///     "key3" => 1234;
21/// );
22/// # assert_eq!(kv.kv.len(), 3);
23/// # assert_eq!(format!("{}", kv.get("key1").unwrap()), "value1");
24/// # assert_eq!(format!("{}", kv.get("key2").unwrap()), "value2");
25/// # assert_eq!(format!("{}", kv.get("key3").unwrap()), "1234");
26/// ```
27#[macro_export]
28macro_rules! kv {
29    ($($k:expr =>  $v:expr;)*) => {
30        $crate::core::KV { kv: std::collections::HashMap::from([ $(($k.into(), $v.into())),* ]) }
31    };
32}
33
34/// Release an `T` from an `Option<T>` if it is not `None`. If it is `None`, return an
35/// `ArgminError` with a provided message.
36#[macro_export]
37macro_rules! check_param {
38    ($param:expr, $msg:expr, $error:ident) => {
39        match $param {
40            None => {
41                return Err($crate::core::ArgminError::$error {
42                    text: $msg.to_string(),
43                }
44                .into());
45            }
46            Some(ref x) => x.clone(),
47        }
48    };
49    ($param:expr, $msg:expr) => {
50        check_param!($param, $msg, NotInitialized)
51    };
52}
53
54/// Create an `ArgminError` with a provided message.
55#[macro_export]
56macro_rules! argmin_error {
57    ($error_type:ident, $msg:expr) => {
58        $crate::core::ArgminError::$error_type {
59            text: $msg.to_string(),
60        }
61        .into()
62    };
63}
64
65/// Create an `ArgminError` with a provided message wrapped in a closure for use in
66/// `.ok_or_else(...)` methods on `Option`s.
67#[macro_export]
68macro_rules! argmin_error_closure {
69    ($error_type:ident, $msg:expr) => {
70        || -> $crate::core::Error { $crate::argmin_error!($error_type, $msg) }
71    };
72}
73
74/// Convert a constant to a float of given precision
75#[macro_export]
76macro_rules! float {
77    ($t:ident, $val:expr) => {
78        $t::from_f64($val).unwrap()
79    };
80    ($val:expr) => {
81        F::from_f64($val).unwrap()
82    };
83}
84
85/// Creates the `bulk_X` methods.
86#[macro_export]
87macro_rules! bulk {
88    ($method_name:tt, $input:ty, $output:ty) => {
89        paste::item! {
90            #[doc = concat!(
91                "Compute `",
92                stringify!($method_name),
93                "` in bulk. ",
94                "If the `rayon` feature is enabled, multiple calls to `",
95                stringify!($method_name),
96                "` will be run in parallel using `rayon`, otherwise they will execute ",
97                "sequentially. If the `rayon` feature is enabled, parallelization can still be ",
98                "turned off by overwriting `parallelize` to return `false`. This can be useful ",
99                "in cases where it is preferable to parallelize only certain parts. ",
100                "Note that even if `parallelize` is set to false, the parameter vectors and the ",
101                "problem are still required to be `Send` and `Sync`. Those bounds are linked to ",
102                "the `rayon` feature. This method can be overwritten.",
103            )]
104            fn [<bulk_ $method_name>]<P>(&self, params: &[P]) -> Result<Vec<$output>, Error>
105            where
106                P: std::borrow::Borrow<$input> + SyncAlias,
107                $output: SendAlias,
108                Self: SyncAlias,
109            {
110                #[cfg(feature = "rayon")]
111                {
112                    if self.parallelize() {
113                        params.par_iter().map(|p| self.$method_name(p.borrow())).collect()
114                    } else {
115                        params.iter().map(|p| self.$method_name(p.borrow())).collect()
116                    }
117                }
118                #[cfg(not(feature = "rayon"))]
119                {
120                    params.iter().map(|p| self.$method_name(p.borrow())).collect()
121                }
122            }
123        }
124
125        #[doc = concat!(
126                    "Indicates whether to parallelize calls to `",
127                    stringify!($method_name),
128                    "` when using `bulk_",
129                    stringify!($method_name),
130                    "`. By default returns true, but can be set manually to `false` if needed. ",
131                    "This allows users to turn off parallelization for certain traits ",
132                    "implemented on their problem. ",
133                    "Note that parallelization requires the `rayon` feature to be enabled, ",
134                    "otherwise calls to `",
135                    stringify!($method_name),
136                    "` will be executed sequentially independent of how `parallelize` is set."
137                )]
138        fn parallelize(&self) -> bool {
139            true
140        }
141    };
142}
143
144/// Implements a simple send and a simple sync test for a given type.
145#[cfg(test)]
146macro_rules! send_sync_test {
147    ($n:ident, $t:ty) => {
148        paste::item! {
149            #[test]
150            #[allow(non_snake_case)]
151            fn [<test_send_ $n>]() {
152                fn assert_send<T: Send>() {}
153                assert_send::<$t>();
154            }
155        }
156
157        paste::item! {
158            #[test]
159            #[allow(non_snake_case)]
160            fn [<test_sync_ $n>]() {
161                fn assert_sync<T: Sync>() {}
162                assert_sync::<$t>();
163            }
164        }
165    };
166}
167
168/// Creates tests for asserting that a struct implements `Send`, `Sync` and `Clone`
169#[cfg(test)]
170#[macro_export]
171macro_rules! test_trait_impl {
172    ($n:ident, $t:ty) => {
173        paste::item! {
174            #[test]
175            #[allow(non_snake_case)]
176            fn [<test_send_ $n>]() {
177                fn assert_send<T: Send>() {}
178                assert_send::<$t>();
179            }
180        }
181
182        paste::item! {
183            #[test]
184            #[allow(non_snake_case)]
185            fn [<test_sync_ $n>]() {
186                fn assert_sync<T: Sync>() {}
187                assert_sync::<$t>();
188            }
189        }
190
191        paste::item! {
192            #[test]
193            #[allow(non_snake_case)]
194            fn [<test_clone_ $n>]() {
195                fn assert_clone<T: Clone>() {}
196                assert_clone::<$t>();
197            }
198        }
199    };
200}
201
202/// Asserts that expression $n leads to an error of type $t and text $s
203#[cfg(test)]
204#[macro_export]
205macro_rules! assert_error {
206    ($n:expr, $t:ty, $s:expr) => {
207        assert_eq!(
208            $n.err().unwrap().downcast_ref::<$t>().unwrap().to_string(),
209            $s
210        );
211    };
212}