Re:Baby Steps: Slowly Porting Musl to Rust
by ThatGeoGuy on Tuesday June 14, 2016 @11:49AM
(#11902804)
I agree with this comment more or less, however I would like to point out that strlen{1,2,3} are all wrong, at least in the capacity that they take pointer differences and return a size_t.
In truth, `ptr_distance` and `return it - s;` should both be of type ptrdiff_t, which is not necessarily the same as size_t. In some ways this is why using an explicit index of type size_t that can be incremented is better, because you can avoid some type casting.
strlen3 is easiest to read, as you can make fairly valid assumptions about the helper functions, and easily confirm them if needed, and it very clearly breaks down the algorithm into its conceptual components. I think it would also be clearest (and thus winner) if the algorithm was slightly more involved, as the gains in clarity would outweigh the gains of having everything defined in just a few lines.
strlen2 is worst, because the helper function gains you very little for the cognitive overload of having the implementation being somewhere else. You are just as well served in this case by a trailing comment, IMO.