by scoutt · 6y ago · 0 comments
So I understand there are runtime checks for out-of-bound reading/writing, correct? This has a cost (overhead) and for embedded systems this is valuable information that should be considered when choosing a language.
I don't know how all of this can be coupled with the embedded ecosystem we are used to work with.
Here, rustc is able to see that we always have a first element, and will actually completely remove the unchecked one, and replace the body with the "checked" one, which has no checks.
For some reason, I can't get it to show the assembly for just the two functions; it always optimzies everything out. Putting it on the rust playground says this:
playground::access_first_element: # @playground::access_first_element
# %bb.0:
pushq %rax
cmpq $2, %rsi
jb .LBB5_2
# %bb.1:
movq %rdi, %rax
addq $4, %rax
popq %rcx
retq
.LBB5_2:
movq %rsi, %rdx
leaq .L__unnamed_2(%rip), %rdi
movl $1, %esi
callq *core::panicking::panic_bounds_check@GOTPCREL(%rip)
ud2
# -- End function
playground::access_first_unchecked: # @playground::access_first_unchecked
# %bb.0:
leaq 4(%rdi), %rax
retq
# -- End function
as you can see, it gets super inlined, and does no work, compared to the bound checked version.I guess in the case of your code, the checks are removed/optimized because the compiler knows the size of the array (since it's static, as in non-dynamically-allocated)?
Probably the out-of-bounds runtime checks will (or should be) enforced when it's about dynamically allocated arrays.