Skip to content

Commit

Permalink
Add Fields::iter_member
Browse files Browse the repository at this point in the history
  • Loading branch information
Fancyflame committed Aug 9, 2024
1 parent 94d74d5 commit 5e3c70d
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::expr::Expr;
use crate::ident::Ident;
use crate::punctuated::{self, Punctuated};
use crate::restriction::{FieldMutability, Visibility};
use crate::spanned::Spanned;
use crate::token;
use crate::ty::Type;

Expand Down Expand Up @@ -106,6 +107,54 @@ impl Fields {
}
}

#[cfg(any(feature = "full", feature = "derive"))]
mod iter_member {
use super::*;
use crate::Member;

impl Fields {
/// Get an iterator over the fields of a struct or variant as [`Member`]s.
/// This iterator can be used to iterate over a named or unnamed struct or
/// variant's fields uniformly.
///
/// The return type can considered as impl [`Iterator<Item = Member>`].
#[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
pub fn iter_member(&self) -> IterMember {
IterMember {
iter: self.iter(),
unnamed_counter: 0,
}
}
}

/// An iterator over the fields of a struct or variant as [`Member`]s.
#[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
#[derive(Clone)]
pub struct IterMember<'a> {
iter: punctuated::Iter<'a, Field>,
unnamed_counter: u32,
}

impl<'a> Iterator for IterMember<'a> {
type Item = Member;

fn next(&mut self) -> Option<Self::Item> {
let field = self.iter.next()?;
match &field.ident {
Some(ident) => Some(Member::Named(ident.clone())),
None => {
let m = Member::Unnamed(crate::Index {
index: self.unnamed_counter,
span: field.ty.span(),
});
self.unnamed_counter += 1;
Some(m)
}
}
}
}
}

impl IntoIterator for Fields {
type Item = Field;
type IntoIter = punctuated::IntoIter<Field>;
Expand Down

0 comments on commit 5e3c70d

Please sign in to comment.