Centralize bounds checking and don't overflow

This does not directly change any of the semantics, but it prevents the
overflow sanitizer from thinking the overflow checks on the buffer
bounds may be overflows themselves.

It also centralizes some checking for clearer code.

Bug: 80146040
Change-Id: Ifd98658d2ee83b2b2544cc8e7f4cbb486b21a575
2 files changed