implement lexicographical ordering for slices of arbitrary types #116
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This generalizes the implementation of
ConstantTimeEqfor[T]to also supportConstantTimeGreaterandConstantTimeLess. I haven't touched the implementation ofConstantTimeEq for [T]as the standalone implementation is more efficient than the multi-purpose code i've added here. However in principle the execution of the code is very similar.I added a utility function
ct_slice_lex_cmp(x, y)which produces acmp::Orderingin time proportional tomin(x.len(), y.len()). I chose this approach rather than implementingConstantTimeGreaterdirectly, because it allows us to also implementConstantTimeLesswithout invoking bothct_eqandct_gt, which would perform up to twice as many loop iterations over both slices.Reasoning
I wrote this PR because I found a need in my project for constant time comparison on fixed-size arrays of bytes (secret data), beyond simple equality checking. Specifically, I needed to check if an elliptic curve secret scalar value represented as
[u8; 32]was larger than the curve order (some fixed[u8; 32]constant).In non-constant time operations, one could simply do
x >= y. I wrotect_slice_lex_cmpto fulfill this duty and realized it might be handy upstream here.PS those formatting changes in
test/mod.rswere automatically applied bycargo fmt. I can revert commit ca90794 if you'd prefer to keep that code formatted as it was before.