allocator_api2/stable/
macros.rs

1/// Creates a [`Vec`] containing the arguments.
2///
3/// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
4/// There are two forms of this macro:
5///
6/// - Create a [`Vec`] containing a given list of elements:
7///
8/// ```
9/// use allocator_api2::vec;
10/// let v = vec![1, 2, 3];
11/// assert_eq!(v[0], 1);
12/// assert_eq!(v[1], 2);
13/// assert_eq!(v[2], 3);
14/// ```
15///
16///
17/// ```
18/// use allocator_api2::{vec, alloc::Global};
19/// let v = vec![in Global; 1, 2, 3];
20/// assert_eq!(v[0], 1);
21/// assert_eq!(v[1], 2);
22/// assert_eq!(v[2], 3);
23/// ```
24///
25/// - Create a [`Vec`] from a given element and size:
26///
27/// ```
28/// use allocator_api2::vec;
29/// let v = vec![1; 3];
30/// assert_eq!(v, [1, 1, 1]);
31/// ```
32///
33/// ```
34/// use allocator_api2::{vec, alloc::Global};
35/// let v = vec![in Global; 1; 3];
36/// assert_eq!(v, [1, 1, 1]);
37/// ```
38///
39/// Note that unlike array expressions this syntax supports all elements
40/// which implement [`Clone`] and the number of elements doesn't have to be
41/// a constant.
42///
43/// This will use `clone` to duplicate an expression, so one should be careful
44/// using this with types having a nonstandard `Clone` implementation. For
45/// example, `vec![Rc::new(1); 5]` will create a vector of five references
46/// to the same boxed integer value, not five references pointing to independently
47/// boxed integers.
48///
49/// Also, note that `vec![expr; 0]` is allowed, and produces an empty vector.
50/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
51/// be mindful of side effects.
52///
53/// [`Vec`]: crate::vec::Vec
54#[cfg(not(no_global_oom_handling))]
55#[macro_export]
56macro_rules! vec {
57    (in $alloc:expr $(;)?) => (
58        $crate::vec::Vec::new_in($alloc)
59    );
60    (in $alloc:expr; $elem:expr; $n:expr) => (
61        $crate::vec::from_elem_in($elem, $n, $alloc)
62    );
63    (in $alloc:expr; $($x:expr),+ $(,)?) => (
64        $crate::boxed::Box::<[_]>::into_vec(
65            $crate::boxed::Box::slice(
66                $crate::boxed::Box::new_in([$($x),+], $alloc)
67            )
68        )
69    );
70    () => (
71        $crate::vec::Vec::new()
72    );
73    ($elem:expr; $n:expr) => (
74        $crate::vec::from_elem($elem, $n)
75    );
76    ($($x:expr),+ $(,)?) => (
77        $crate::boxed::Box::<[_]>::into_vec(
78            $crate::boxed::Box::slice(
79                $crate::boxed::Box::new([$($x),+])
80            )
81        )
82    );
83}