Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unsafe code from macro expansions #818

Merged
merged 3 commits into from
Dec 6, 2024

Conversation

nbaksalyar
Copy link
Contributor

@nbaksalyar nbaksalyar commented Dec 4, 2024

Motivation

  • The sol! macro cannot be used in projects with strict unsafe code policies.
  • The current unsafe implementation of abi_decode_raw is not efficient: binary search (O(log n)) is slower than a simple jump table (O(1) or O(n) at worst, for e.g. compare the MIR/asm output).

Solution

  • Switch abi_decode_raw to use a constant jump table instead of a runtime binary search.
  • Generate safe code to convert between enum variants and u8 statically.
  • Make the as_u8 function constant.
  • Additionally, allow clippy::empty_structs_with_brackets in the generated code.

PR Checklist

  • Added Tests
  • Added Documentation
  • Breaking changes

* Use a static match to convert between enum variants and `u8`

* Use a static match in `abi_decode_raw`
@DaniPopes
Copy link
Member

DaniPopes commented Dec 6, 2024

The current unsafe implementation of abi_decode_raw is not efficient: binary search (O(log n)) is slower than a simple jump table (O(1) or O(n) at worst, for e.g. compare the MIR/asm output).

This is not true, I would recommend you compare the LLVM IR and/or assembly output for a large calls enum, for example Foundry's Vm. The binary search gets unrolled, made branchless and constant-time at compile-time, while the switch gets codegen'd as a binary search regardless because all the match arms have different code sizes.

In this case we can just remove the get_unchecked because the optimizer knows that the returned index is guaranteed to be in-bounds.

The other changes are fine.

@DaniPopes DaniPopes enabled auto-merge (squash) December 6, 2024 23:26
@DaniPopes DaniPopes merged commit dc0de77 into alloy-rs:main Dec 6, 2024
30 checks passed
@nbaksalyar nbaksalyar deleted the remove-unsafe-code branch December 7, 2024 04:50
@nbaksalyar
Copy link
Contributor Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants