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

Avoid redundant bounds checks #110

Merged
merged 2 commits into from
Oct 31, 2024
Merged

Avoid redundant bounds checks #110

merged 2 commits into from
Oct 31, 2024

Conversation

kornelski
Copy link
Contributor

        self.slice[self.pos] = first;
        self.slice[self.pos + 1] = second;
        self.slice[self.pos + 2] = third;
        self.slice[self.pos + 3] = fourth;

Code like this performs bounds check four times, and generates panicking code for four unique locations, which is relatively bloated for something as simple as writing four bytes.

OTOH assigning to a slice that is known to be 4 bytes long doesn't need extra bounds checks. split_at_mut(4) can create such slice, and advance the position in one go.

I've also eliminated separate tracking of start position via pos field by advancing the slice itself. To get the amount of bytes written I use a pointer comparison. It doesn't require unsafe, because the pointer is only used as an integer, and not as a pointer, and the address difference is guaranteed to be valid for positions within a single slice.

https://rust.godbolt.org/z/o95vE7rWT

@hsivonen hsivonen merged commit 8cec3a5 into hsivonen:main Oct 31, 2024
4 checks passed
@hsivonen
Copy link
Owner

Thank you!

@kornelski kornelski deleted the bounds branch November 1, 2024 17:02
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