Use constant size generic parameter for random bytes generation #2910
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.
All uses of
get_random()
were in the form of:&get_random(vec![0u8; SIZE])
with
SIZE
being a constant.Building a
Vec
is unnecessary for two reasons. First, it uses a very short-lived dynamic memory allocation. Second, aVec
is a resizable object, which is useless in those context when random data have a fixed size and will only be read.get_random_bytes()
takes a constant as a generic parameter and returns an array with the requested number of random bytes.Stack safety analysis: the random bytes will be allocated on the caller stack for a very short time (until the encoding function has been called on the data). In some cases, the random bytes take less room than the
Vec
did (aVec
is 24 bytes on a 64 bit computer). The maximum used size is 180 bytes, which makes it for 0.008% of the default stack size for a Rust thread (2MiB), so this is a non-issue.Also, most of the uses of those random bytes are to encode them using an
Encoding
. The functioncrypto::encode_random_bytes()
generates random bytes and encode them with the providedEncoding
, leading to code deduplication.generate_id()
has also been converted to use a constant generic parameter as well since the length of the requested String is always a constant.