blob: 564997204cba92b7b41dc59bf789c846ac601d83 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![deny(missing_docs)]
//! Utility macros that should be in std but is not.
use std::iter::repeat;
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::Parse;
use syn::{parse_macro_input, LitChar, LitInt, Token};
/// Repeats a character N number of times resulting in a string literal.
///
/// # Arguments
/// Seperated by commas.
///
/// - The character to repeat
/// - Number of times to repeat it.
///
/// # Examples
/// ```
/// # use utility_macros::repeat_char;
///
/// let eight_o = repeat_char!('o', 8);
///
/// assert_eq!(eight_o, "oooooooo");
/// ```
#[proc_macro]
pub fn repeat_char(input: TokenStream) -> TokenStream
{
let RepeatCharMacroArgs { character, count } =
parse_macro_input!(input as RepeatCharMacroArgs);
let repeated = repeat(character.value()).take(count).collect::<String>();
quote! {
#repeated
}
.into()
}
struct RepeatCharMacroArgs
{
character: LitChar,
count: usize,
}
impl Parse for RepeatCharMacroArgs
{
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self>
{
let character = input.parse::<LitChar>()?;
input.parse::<Token![,]>()?;
let count = input.parse::<LitInt>()?.base10_parse::<usize>()?;
Ok(Self { character, count })
}
}
|