Optional Bounds Checking

In a performance sensitive situation, I am doing slice element accesses. I get a significant speedup using get_unchecked rather than [i].

The accesses don't follow a clear pattern, so I haven't figured out a way of using iterators.

While I "know" that I have no bugs in my code, I would still love to be able to have the bounds checking in debug builds, but not have them in release builds. Is there a way of doing this - ideally one which preserves the [i] notation, but wraps it in some big scary "you better know what you are doing because you are optionally breaking security here" syntax, like "unsafe" + "get_unchecked" already does non-optionally?

You could create a wrapper type and implement Index on it by delegating to the inner type's get_unchecked. Then, I'd recommend keeping the type private and constructing it unsafe.

It's a good idea to throw in some debug_assert!()s so a debug build will still do bounds checks. That way you can catch indexing bugs during development while ignoring bounds checks for production.

1 Like