argmin/core/
macros.rs

1// Copyright 2018-2020 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 `ArgminKV` at compile time in order to avoid pushing to the `kv` vector.
11#[macro_export]
12macro_rules! make_kv {
13    ($($k:expr =>  $v:expr;)*) => {
14        ArgminKV { kv: vec![ $(($k, format!("{:?}", $v))),* ] }
15    };
16}
17
18/// Release an `T` from an `Option<T>` if it is not `None`. If it is `None`, return an
19/// `ArgminError` with a message that needs to be provided.
20#[macro_export]
21macro_rules! check_param {
22    ($param:expr, $msg:expr, $error:ident) => {
23        match $param {
24            None => {
25                return Err(ArgminError::$error {
26                    text: $msg.to_string(),
27                }
28                .into());
29            }
30            Some(ref x) => x.clone(),
31        }
32    };
33    ($param:expr, $msg:expr) => {
34        check_param!($param, $msg, NotInitialized);
35    };
36}
37
38/// Implements a simple send and a simple sync test for a given type.
39#[cfg(test)]
40macro_rules! send_sync_test {
41    ($n:ident, $t:ty) => {
42        paste::item! {
43            #[test]
44            #[allow(non_snake_case)]
45            fn [<test_send_ $n>]() {
46                fn assert_send<T: Send>() {}
47                assert_send::<$t>();
48            }
49        }
50
51        paste::item! {
52            #[test]
53            #[allow(non_snake_case)]
54            fn [<test_sync_ $n>]() {
55                fn assert_sync<T: Sync>() {}
56                assert_sync::<$t>();
57            }
58        }
59    };
60}
61
62/// Reuse a list of trait bounds by giving it a name,
63/// e.g. trait_bound!(CopyAndDefault; Copy, Default);
64#[macro_export]
65macro_rules! trait_bound {
66    ($name:ident ; $head:path $(, $tail:path)*) => {
67        #[allow(missing_docs)]
68        pub trait $name : $head $(+ $tail)* {}
69        impl<T> $name for T where T: $head $(+ $tail)* {}
70    };
71}