default_constructor/
lib.rs

1#![doc = include_str!("../README.md")]
2#![no_std]
3mod convert;
4pub use convert::{infer_into, InferInto, StandardConverters};
5pub use default_constructor_macros::meta_default_constructor;
6/// Standard intermediate functions that can be called via the `@name` syntax.
7///
8/// This enables conversion chains like `&str --into--> String --@some--> Option<String>`.
9pub mod effects {
10    extern crate alloc;
11
12    /// Construct a `Box`.
13    #[cfg(feature = "std")]
14    pub fn boxed<T>(item: T) -> alloc::boxed::Box<T> {
15        alloc::boxed::Box::new(item)
16    }
17
18    /// Construct an `Rc`.
19    #[cfg(feature = "std")]
20    pub fn rc<T>(item: T) -> alloc::rc::Rc<T> {
21        alloc::rc::Rc::new(item)
22    }
23
24    /// Construct an `Arc`.
25    #[cfg(feature = "std")]
26    pub fn arc<T>(item: T) -> alloc::sync::Arc<T> {
27        alloc::sync::Arc::new(item)
28    }
29
30    /// Construct a `Cow`.
31    #[cfg(feature = "std")]
32    pub fn cow<T: Clone>(item: T) -> alloc::borrow::Cow<'static, T> {
33        alloc::borrow::Cow::Owned(item)
34    }
35
36    /// Construct a `Some`.
37    pub fn some<T>(item: T) -> Option<T> {
38        Option::Some(item)
39    }
40
41    /// Construct an iterator from an array.
42    ///
43    /// This is magic since this also enables macro recursion on array literals.
44    ///
45    /// `[a, b, c] -> [a.into(), b.into(), c.into()].into_iter().collect()`.
46    pub fn arr<T, I: IntoIterator<Item = T> + FromIterator<T>, const N: usize>(item: [T; N]) -> I {
47        item.into_iter().collect()
48    }
49}
50
51/// A standard constructor that uses [`Into`].
52///
53/// # Syntax
54///
55/// ```
56/// # /*
57/// construct! {
58///     Student {
59///         name: "Timmy",
60///         age: 10,
61///         father : {
62///             name: "Tommy",
63///             age: 35,
64///         }
65///     }
66/// }
67/// # */
68/// ```
69#[macro_export]
70macro_rules! construct {
71    ($($tt: tt)*) => {
72        {
73            use $crate::effects::*;
74            $crate::meta_default_constructor! {
75                [::std::convert::Into::into]
76                $($tt)*
77            }
78        }
79    };
80}
81
82/// A standard constructor that uses [`InferInto`].
83///
84/// [`InferInto`] is inference based and will fail if multiple implementations
85/// of the same conversion exists.
86///
87/// # Syntax
88///
89/// ```
90/// # /*
91/// infer_construct! {
92///     Student {
93///         name: "Timmy",
94///         age: 10,
95///         father : {
96///             name: "Tommy",
97///             age: 35,
98///         }
99///     }
100/// }
101/// # */
102/// ```
103#[macro_export]
104macro_rules! infer_construct {
105    ($($tt: tt)*) => {
106        {
107            use $crate::effects::*;
108            $crate::meta_default_constructor! {
109                [$crate::infer_into]
110                $($tt)*
111            }
112        }
113    };
114}