top | item 43917535

(no title)

genrilz | 9 months ago

The reason '+ 1' is fine in the example you gave is that length is always less than or equal to capacity. If you follow 'grow_one' which was earlier in the function to grow the capacity by one if needed, you will find that it leads to the checked addition in [0], which returns an error that [1] catches and turns into a panic. So using '+1' prevents a redundant check in release mode while still adding the check in debug mode in case future code changes break the 'len <= capacity' invariant.

Of course, if you don't trust the standard library, you can turn on overflow checks in release mode too. However, the standard library is well tested and I think most people would appreciate the speed from eliding redundant checks.

  [0]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#651
  [1]: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#567

discuss

order

No comments yet.