Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a .len() function #274

Closed
jmg-duarte opened this issue Apr 16, 2022 · 3 comments
Closed

Implement a .len() function #274

jmg-duarte opened this issue Apr 16, 2022 · 3 comments

Comments

@jmg-duarte
Copy link

I'm currently using this crate for "incremental" options for an application I'm writing - to that end, I need to iterate over the set flags in the structure.

I've started implementing an iterator which simply goes through the bits, right to left and yields an Option<BitFlag> for each, signaling whether it is set or not - to achieve this, having a length method in the generated structure would help immensely since it allows me to know when I've reached the structure end.

Would there be interest in implementing this?

@jmg-duarte
Copy link
Author

I've written a "workaround" .len():

const fn len() -> usize {
    let mut all = Self::all().bits();
    let mut idx = 0;
    while all != 0 {
        all >>= 1;
        idx += 1;
    }
    idx
}

@KodrAus
Copy link
Member

KodrAus commented Apr 23, 2022

Hi @jmg-duarte 👋

This unfortunately starts to get tricky when you have flags that cover multiple bits, which is something that bitflags allows even if it's not the most common case. I think that's what's stalled most attempts to implement a general iterator for all kinds of flags. The latest attempt is #278, which seems pretty close.

@KodrAus
Copy link
Member

KodrAus commented May 4, 2022

Since #278 is merged we can now write flags.iter().count(). I think this is nice and clear and communicates that the length you get is calculated rather than intrinsic.

We're currently working towards a 2.0.0 release that will include this and some other breaking changes for better future-proofing. If you'd like to keep track of where that's at you can follow along #262

@KodrAus KodrAus closed this as completed May 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants