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

fix: allow any int type for indexing #57

Closed
wants to merge 1 commit into from

Conversation

henryiii
Copy link
Contributor

This expands the current panic if the index is out of bounds into panic if a negative index is given, and allows negative indexes (along with other bit lengths).

This expands the current panic if the index is out of bounds into panic if a negative index is given, and allows negative indexes (along with other bit lengths).

Signed-off-by: Henry Schreiner <[email protected]>
Copy link
Owner

@becheran becheran left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bit similar to the discussion in #60

I am not sure if adding this feature would be in the scope of the goal of mimicing vec, but in a 2D data object.

The added try_into code will also add a bit of runtime overhead. Although, to be fair, it will be fairly low. Still. I am not sure if using an unsigned index is really that much of requirement. It would also be fairly simply to convert from signed to unsigned before indexing on the calling side and handle issues such as overflows outside of grid.

@henryiii
Copy link
Contributor Author

I was expecting that try_into should be implemented as nothing and optimize away for matching sizes. The extra cost should only occur if it's converting. (Though I agree if that's not the case!)

@henryiii
Copy link
Contributor Author

It looks like the ASM is different, I tried these two:

use core::ops::Index;

struct A {
    a: Vec<u8>,
}

impl<T: TryInto<usize>> Index<(T, T)> for A {
    type Output = u8;

    #[inline]
    fn index(&self, (row, col): (T, T)) -> &u8 {
        &self.a[row.try_into().ok().unwrap()*col.try_into().ok().unwrap()]
    }
}

/*
struct A {
    a: Vec<u8>,
}

impl Index<(usize, usize)> for A {
    type Output = u8;

    #[inline]
    fn index(&self, (row, col): (usize, usize)) -> &u8 {
        &self.a[row*col]
    }
}
*/

fn main() {
    let v = A{a: vec![0,1,2,3,4,5,6,7]};
    println!("{}", v[(3,2)]);
}

@henryiii henryiii closed this Dec 18, 2024
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

Successfully merging this pull request may close these issues.

2 participants