Avoid heap allocations in ValueRipemd160
#125
Merged
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.
Problems
The
Ripemd160
class was replaced byValueRipemd160
in PR #121. However, this change presents a few issues:ValueRipemd160
is defined as a struct, yet it contains array fields allocated on the heap.ValueRipemd160
will have invalid states when copied, which constitutes a breaking change.Solutions
To address these issues, the following solutions are proposed:
ValueRipemd160
fromstruct
toref struct
. By imposing the constraint that this struct can only exist on the stack, it reduces the possibility of common mistakes such as unintended defensive copying, and enables the use of stack space as a buffer.ComputeHashDigest(Span<byte>)
method for safer and simpler computation of RIPEMD-160 hash. Since handling mutable structs and stack-based buffers is prone to errors, this method allows for simple use cases without directly manipulating instances of theValueRipemd160
struct.Span<T>
instead of arrays, allowing stack allocation. By passing buffers allocated on the stack usingstackalloc
asSpan<T>
to the constructor, heap allocation can be completely avoided.Benchmark
Benchmark code