Skip to content

mut reborrow? #83

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

Closed
Rudxain opened this issue Apr 22, 2024 · 3 comments
Closed

mut reborrow? #83

Rudxain opened this issue Apr 22, 2024 · 3 comments

Comments

@Rudxain
Copy link

Rudxain commented Apr 22, 2024

Does the following qualify? (Edition 2021)

pub fn xor_hasher<'a, T>(inp: &'a [T], sbox: &mut [T])
where
    T: core::ops::BitXorAssign<&'a T>,
{
    let len = sbox.len();
    if len == 0 {
        return;
    };
    for chunk in inp.chunks(len) {
        chunk.iter().zip(sbox).for_each(|(i, s)| *s ^= i);
    }
}

Doesn't compile because sbox moves into zip, so &mut *sbox must be used instead. I find this silly, but "silly" isn't enough to be considered "obscure"

@Rudxain
Copy link
Author

Rudxain commented Apr 25, 2024

I've been experimenting with this. The results are weirder...

// error
fn xor0<'a, T: 'a, I: IntoIterator<Item = &'a T>>(inp: I, sbox: &mut [T])
where
    T: core::ops::BitXorAssign<&'a T>,
{
    for _ in 0..3 {
        inp.into_iter().zip(sbox).for_each(|(i, s)| *s ^= i);
    }
}

// error
fn xor1<I: Iterator<Item = u8> + Copy>(inp: I, sbox: &mut [u8]) {
    for _ in 0..3 {
        inp.zip(sbox).for_each(|(i, s)| *s ^= i);
    }
}

fn drop_ref(sbox: &mut [u8]) {}
// works???
fn drop_multi(sbox: &mut [u8]) {
    for _ in 0..3 {
        // if sbox isn't `Copy`, then why does this compile?
        // it should move into `drop_ref`, requiring a fresh reborrow
        drop_ref(sbox); // replace by `drop` to trigger error
    }
}

@dtolnay
Copy link
Owner

dtolnay commented Jan 25, 2025

Thank you for the suggestion! "Does it compile or not" flavor of questions do not tend to make good quiz questions so I would prefer not to include a question on this topic, but I appreciate the contribution.

@dtolnay dtolnay closed this as completed Jan 25, 2025
@Rudxain
Copy link
Author

Rudxain commented Mar 17, 2025

To anyone with the same confusion as me, I've found this blog which explains really well what's happening. See also. Related: rust-lang/reference#788

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