Skip to content

Commit

Permalink
Fix EnumIter for enums named Option (#300)
Browse files Browse the repository at this point in the history
Co-authored-by: Horaci Macias <hmacias@avaya.com>
  • Loading branch information
horacimacias and hmacias-avaya authored Oct 15, 2023
1 parent 0199235 commit 42c1666
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 5 additions & 5 deletions strum_macros/src/macros/enum_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
}

impl #impl_generics #iter_name #ty_generics #where_clause {
fn get(&self, idx: usize) -> Option<#name #ty_generics> {
fn get(&self, idx: usize) -> ::core::option::Option<#name #ty_generics> {
match idx {
#(#arms),*
}
Expand All @@ -112,16 +112,16 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
impl #impl_generics Iterator for #iter_name #ty_generics #where_clause {
type Item = #name #ty_generics;

fn next(&mut self) -> Option<<Self as Iterator>::Item> {
fn next(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> {
self.nth(0)
}

fn size_hint(&self) -> (usize, Option<usize>) {
fn size_hint(&self) -> (usize, ::core::option::Option<usize>) {
let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx };
(t, Some(t))
}

fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> {
fn nth(&mut self, n: usize) -> ::core::option::Option<<Self as Iterator>::Item> {
let idx = self.idx + n + 1;
if idx + self.back_idx > #variant_count {
// We went past the end of the iterator. Freeze idx at #variant_count
Expand All @@ -143,7 +143,7 @@ pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
}

impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause {
fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
fn next_back(&mut self) -> ::core::option::Option<<Self as Iterator>::Item> {
let back_idx = self.back_idx + 1;

if self.idx + back_idx > #variant_count {
Expand Down
13 changes: 13 additions & 0 deletions strum_tests/tests/enum_iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,16 @@ fn crate_module_path_test() {

assert_eq!(expected, results);
}

#[test]
fn enum_iter_option() {
#[derive(Debug, Eq, PartialEq, EnumIter)]
enum Option {
BluePill,
RedPill,
}
let results = Option::iter().collect::<Vec<_>>();
let expected = vec![Option::BluePill, Option::RedPill];

assert_eq!(expected, results);
}

0 comments on commit 42c1666

Please sign in to comment.