In git-crypt there is a function to compare char arrays that's called leakless_equals_chars which visits all elements of array before reporting back if they are the same or not:
My understanding is that they are using volatile to prevent compiler from optimizing so that while loop visits all members, this way we are not leaking any info on how different the arrays are by returning early upon first non-equal bytes.
Can the following rust snippet achieve the same goal without using ptr::read/write_volatile?
In theory, with your snippet, there's nothing preventing the compiler from optimizing the loop to return early if any of the a ^ bs are nonzero. I'm not sure whether any current compilers actually implement such an optimization – I did some quick testing on gcc.godbolt.org and didn't find anything interesting – but a future compiler could. By contrast, the C version uses volatile to ensure the compiler treats the intermediate result as a 'black box'.
The TL;DR I think is that writing code, which is "officially" constant time is impossible, so the only way to guarantee constant-timentess is to directly verify the assembly.
And even that may not be enough, as some low-level machine implementations have data-dependent timing variance of single instructions (e.g., multiply on ARM or PPC).
Thanks for pointing out that crate.
I don't need to avoid std::ptr, question was more on how possibly Rust facilities could be used to avoid using C-style volatile trick to stop compiler from optimizing and getting constant time.
Additionally in the context I was doing this, avoiding that unsafe keyword would be a big bonus. However based on above answers it seems this is a problem without a 100 reliable solution.