cds/arrayvec/macros.rs
1/// Creates an [`ArrayVec`] containing the arguments.
2///
3/// `array_vec!` macro allows creation of an `ArrayVec` using syntax similar to that of the standard
4/// array.
5///
6/// # Examples
7///
8/// 1. `array_vec![CAPACITY; TYPE]` - create an empty `ArrayVec` with given capacity and type:
9///
10/// ```rust
11/// # use cds::array_vec;
12/// let a = array_vec![3; u64];
13/// assert_eq!(a.capacity(), 3);
14/// assert_eq!(a.len(), 0);
15/// ```
16///
17/// 2. `array_vec![CAPACITY; TYPE; ELEM+]` - create an `ArrayVec` with given capacity, type and
18/// elements:
19///
20/// ```rust
21/// # use cds::array_vec;
22/// let a = array_vec![5; u64; 17];
23/// assert_eq!(a.capacity(), 5);
24/// assert_eq!(a.len(), 1);
25/// assert_eq!(a[0], 17u64);
26/// ```
27///
28/// 3. `array_vec![CAPACITY;]` - create an empty `ArrayVec` with given capacity, let the compiler
29/// derive the type:
30///
31/// ```rust
32/// # use cds::array_vec;
33/// let mut a = array_vec![3;];
34/// a.push("str");
35/// assert_eq!(a.capacity(), 3);
36/// assert_eq!(a.len(), 1);
37/// assert_eq!(a[0], "str");
38/// ```
39///
40/// 4. `array_vec![CAPACITY; ELEM+]` - create an `ArrayVec` with given capacity and elements,
41/// let the compiler derive the type:
42///
43/// ```rust
44/// # use cds::array_vec;
45/// let a = array_vec![32; 9, 8, 7];
46/// assert_eq!(a.capacity(), 32);
47/// assert_eq!(a.len(), 3);
48/// assert_eq!(&a[..], &[9, 8, 7]);
49/// ```
50///
51/// 5. `array_vec!` panics if the number of elements exceeds the requested capacity:
52///
53/// ```should_panic
54/// # use cds::array_vec;
55/// array_vec![0; u64; 1];
56/// ```
57///
58/// # Panics
59///
60/// The macro panics if the number of elements exceeds the requested capacity.
61///
62/// [`ArrayVec`]: crate::arrayvec::ArrayVec
63#[cfg_attr(docsrs, doc(cfg(feature = "arrayvec")))]
64#[macro_export]
65macro_rules! array_vec {
66 ($c:expr; $t:ty) => {{
67 cds::arrayvec::ArrayVec::<$t, $c>::new()
68 }};
69 ($c:expr; $t:ty; $($e:expr),+ $(,)?) => {{
70 cds::arrayvec::ArrayVec::<$t, $c>::try_from([$($e),*])
71 .expect("insufficient capacity")
72 }};
73 ($c:expr;) => {{
74 cds::arrayvec::ArrayVec::<_, $c>::new()
75 }};
76 ($c:expr; $($e:expr),+ $(,)?) => {{
77 cds::arrayvec::ArrayVec::<_, $c>::try_from([$($e),*])
78 .expect("insufficient capacity")
79 }};
80}