Add compact string encoding library #320
Open
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.
Description
Adds utils/PackedStringLib.sol - a library for efficiently encoding strings that are <=31 bytes.
Solidity's built-in mechanism for accessing storage strings is efficient when strings can be any size, but in practice most tend to be quite small and static. This means that all of the additional code for determining the type of string (single or multiple word), looping over words and hashing each index to get the slot, goes totally unused. Surprisingly, this can add up to several hundred (or even thousand!) bytes depending on your optimization settings, and can really eat into available contract space.
Below is a comparison of the simplest use-case (retrieving a contract's name) with packed vs. standard strings and constant/immutable vs. storage.
I tried to stick to the coding conventions as much as possible, but this file has a lot more comments than most - had a bit of an ADHD moment. @transmissions11 if you prefer to keep to the clean aesthetic I'm happy to remove them.
I'm also a little new to Forge, so I'd appreciate a second opinion on whether there are any gaps in the testing.
Checklist
Ensure you completed all of the steps below before submitting your pull request:
forge snapshot
?npm run lint
?forge test
?