feat(nifs): Foldable
wrapper for trace
#357
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.
Motivation
During the implementation of #316 we added a condition that consistency tokens started to be collapsed differently than all other instances, which in fact added a constraint to
nifs::FS
that now only traces with two elements in the first instance column can be collapsed. Otherwise, the behavior is undefined. This PR solves the problem of checking this restrictionOverview
The newtype pattern was used to solve the problem in this way. An example of using such a pattern is the
NonZero<T>
wrapper from the standard library. Now, instead of checking in all functions that involve consistency tokens, we acceptvanilla::FoldablePlonkTrace
instead ofPlonkTrace
. This type can only be created with a single constructor, which performs the trace validity check at the point of creation.For instance:
This pattern encapsulates the validation logic within the
FoldablePlonkTrace
type, ensuring that all instances ofFoldablePlonkTrace
are valid by construction. This approach significantly reduces verbosity and potential for error, improving both safety and readability of the code. Moreover, it ensures that the invariant (traces having two elements in the first instance column) is enforced in a single place, thus avoiding scattered checks throughout the codebase.Here, the
new
method ofFoldablePlonkInstance
ensures that it can only be instantiated if thePlonkInstance
meets the specific requirement. This is less verbose than returning an error through multiple layers of modules and provides a more accurate check compared to panicking if an implicit invariant is violated.