Skip to content

Comments

Avoid redundant bounds checks#110

Merged
hsivonen merged 2 commits intohsivonen:mainfrom
kornelski:bounds
Oct 31, 2024
Merged

Avoid redundant bounds checks#110
hsivonen merged 2 commits intohsivonen:mainfrom
kornelski:bounds

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
@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