Skip to content

Commit

Permalink
iterator: add cfg to tests
Browse files Browse the repository at this point in the history
  • Loading branch information
arturoc committed Apr 26, 2022
1 parent 5f753e1 commit 6656792
Showing 1 changed file with 57 additions and 1 deletion.
58 changes: 57 additions & 1 deletion src/lib.rs
Expand Up @@ -772,6 +772,57 @@ macro_rules! __impl_bitflags {
})
}

/// Returns an iterator over all the flags names as &'static str in this set.
pub fn iter_names(mut self) -> impl Iterator<Item = &'static str> {
const NUM_FLAGS: usize = {
#[allow(unused_mut)]
let mut num_flags = 0;

$(
#[allow(unused_doc_comments, unused_attributes)]
$(#[$attr $($args)*])*
{
num_flags += 1;
}
)*

num_flags
};
const OPTIONS: [$BitFlags; NUM_FLAGS] = [
$(
#[allow(unused_doc_comments, unused_attributes)]
$(#[$attr $($args)*])*
$BitFlags::$Flag,
)*
];
#[allow(unused_doc_comments, unused_attributes)]
const OPTIONS_NAMES: [&'static str; NUM_FLAGS] = [
$(
$(#[$attr $($args)*])*
$crate::_core::stringify!($Flag),
)*
];
let mut start = 0;

$crate::_core::iter::from_fn(move || {
if self.is_empty() || NUM_FLAGS == 0 {
None
}else{
for (flag, flag_name) in OPTIONS[start..NUM_FLAGS].iter().copied()
.zip(OPTIONS_NAMES[start..NUM_FLAGS].iter().copied())
{
start += 1;
if self.contains(flag) {
self.remove(flag);
return Some(flag_name)
}
}

None
}
})
}

}

impl $crate::_core::ops::BitOr for $BitFlags {
Expand Down Expand Up @@ -1847,15 +1898,20 @@ mod tests {
const ONE = 0b001;
const TWO = 0b010;
const THREE = 0b100;
#[cfg(windows)]
const FOUR_WIN = 0b1000;
#[cfg(unix)]
const FOUR_UNIX = 0b10000;
}
}

let flags = Flags::all();
assert_eq!(flags.iter().count(), 3);
assert_eq!(flags.iter().count(), 4);
let mut iter = flags.iter();
assert_eq!(iter.next().unwrap(), Flags::ONE);
assert_eq!(iter.next().unwrap(), Flags::TWO);
assert_eq!(iter.next().unwrap(), Flags::THREE);
assert_eq!(iter.next().unwrap(), Flags::FOUR_UNIX);
assert_eq!(iter.next(), None);

let flags = Flags::empty();
Expand Down

0 comments on commit 6656792

Please sign in to comment.