Skip to content

Commit

Permalink
Implement IntoIterator for Tokens
Browse files Browse the repository at this point in the history
This allows a Tokens to be passed to Tokens::append_all.

    tokens.append_all(quote!(...));
  • Loading branch information
dtolnay committed Jan 8, 2018
1 parent 5520c53 commit 4047de7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,35 @@ impl From<Tokens> for proc_macro::TokenStream {
}
}

/// Allows a `Tokens` to be passed to `Tokens::append_all`.
impl IntoIterator for Tokens {
type Item = TokenTree;
type IntoIter = private::IntoIter;

fn into_iter(self) -> Self::IntoIter {
private::into_iter(self.tts.into_iter())
}
}

mod private {
use std::vec;
use proc_macro2::TokenTree;

pub struct IntoIter(vec::IntoIter<TokenTree>);

pub fn into_iter(tts: vec::IntoIter<TokenTree>) -> IntoIter {
IntoIter(tts)
}

impl Iterator for IntoIter {
type Item = TokenTree;

fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
}

impl Display for Tokens {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&TokenStream::from(self.clone()), formatter)
Expand Down
8 changes: 8 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,11 @@ fn test_closure() {
let tokens = quote! { #(#fields)* };
assert_eq!("__field0 __field1 __field2", tokens.to_string());
}

#[test]
fn test_append_tokens() {
let mut a = quote!(a);
let b = quote!(b);
a.append_all(b);
assert_eq!("a b", a.to_string());
}

0 comments on commit 4047de7

Please sign in to comment.