Created
April 29, 2020 22:12
-
-
Save jonhoo/ec57882a976a2d2a92b3138ea25cd45a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_export] | |
macro_rules! avec { | |
($($element:expr),*) => {{ | |
// check that count is const | |
const C: usize = $crate::count![@COUNT; $($element),*]; | |
#[allow(unused_mut)] | |
let mut vs = Vec::with_capacity(C); | |
$(vs.push($element);)* | |
vs | |
}}; | |
($($element:expr,)*) => {{ | |
$crate::avec![$($element),*] | |
}}; | |
($element:expr; $count:expr) => {{ | |
let mut vs = Vec::new(); | |
vs.resize($count, $element); | |
vs | |
}}; | |
} | |
#[macro_export] | |
#[doc(hidden)] | |
macro_rules! count { | |
(@COUNT; $($element:expr),*) => { | |
<[()]>::len(&[$($crate::count![@SUBST; $element]),*]) | |
}; | |
(@SUBST; $_element:expr) => { () }; | |
} | |
#[test] | |
fn empty_vec() { | |
let x: Vec<u32> = avec![]; | |
assert!(x.is_empty()); | |
} | |
#[test] | |
fn single() { | |
let x: Vec<u32> = avec![42]; | |
assert!(!x.is_empty()); | |
assert_eq!(x.len(), 1); | |
assert_eq!(x[0], 42); | |
} | |
#[test] | |
fn double() { | |
let x: Vec<u32> = avec![42, 43]; | |
assert!(!x.is_empty()); | |
assert_eq!(x.len(), 2); | |
assert_eq!(x[0], 42); | |
assert_eq!(x[1], 43); | |
} | |
#[test] | |
fn trailing() { | |
let _: Vec<&'static str> = avec![ | |
"lakdjwaidjiwalfjhawligfjawilfjawlifwjalwijwfalijawfiljfaew", | |
"lakdjwaidjiwalfjhawligfjawilfjawlifwjalwijwfalijawfiljfaew", | |
"lakdjwaidjiwalfjhawligfjawilfjawlifwjalwijwfalijawfiljfaew", | |
"lakdjwaidjiwalfjhawligfjawilfjawlifwjalwijwfalijawfiljfaew", | |
"lakdjwaidjiwalfjhawligfjawilfjawlifwjalwijwfalijawfiljfaew", | |
]; | |
} | |
#[test] | |
fn clone_2() { | |
let x: Vec<u32> = avec![42; 2]; | |
assert!(!x.is_empty()); | |
assert_eq!(x.len(), 2); | |
assert_eq!(x[0], 42); | |
assert_eq!(x[1], 42); | |
} | |
#[test] | |
fn clone_2_nonliteral() { | |
let mut y = Some(42); | |
let x: Vec<u32> = avec![y.take().unwrap(); 2]; | |
assert!(!x.is_empty()); | |
assert_eq!(x.len(), 2); | |
assert_eq!(x[0], 42); | |
assert_eq!(x[1], 42); | |
} | |
/// ```compile_fail | |
/// let x: Vec<u32> = vecmac::avec![42; "foo"]; | |
/// ``` | |
#[allow(dead_code)] | |
struct CompileFailTest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We appreciate what you do. Thanks.