seanmonstar / httparse

A push parser for the HTTP 1.x protocol in Rust.
https://docs.rs/httparse
Apache License 2.0
569 stars 110 forks source link

Reduce Usage of Unsafe #86

Open CalebLBaker opened 3 years ago

CalebLBaker commented 3 years ago

Remove unnecessary usage of unsafe and replace some unsafe code with equivalent safe code.

The safe implementation of iter::Bytes::slice_skip proposed by this pull request has been benchmarked to be (slightly) slower than the currently used implementation, so if performance is an issue I can revert the changes to that particular method while still keeping my other changes.

shrink cannot be written without using unsafe (there are issues related to temporarily mutably borrowing the slice multiple times simultaneously), so I am ignoring it in this pull request. I might come back later and look at how shrink is used to see if something safer can be used instead.

I also ignored usage of str::from_utf8_unchecked since it seems apparent that whenever it is used in this crate the bytes passed in have already been checked for utf-8 compliance and so checking again would be redundant.

seanmonstar commented 3 years ago

Thanks so much for filing this! I'll take a look through now :)

seanmonstar commented 3 years ago

I was curious how the extra bounds checks would perform, so when I run the benchmarks of master vs this PR, here's what I see:

CalebLBaker commented 3 years ago

That looks similar to the results that I got from running the benchmarks. I've played around with benchmarking different subsets of the pull request and the greatest portion of the performance difference definitely seems to come from slice_skip.