✨ Add `set` and `delete_` to native bytes/string in storage
Description
Add set and delete_ functions to simplify handling of bytes and string storage references in LibBytes and LibString. These changes enable efficient and memory-safe operations when assigning or deleting storage references directly.
Rationale
As the following example shows, Solidity only allows assignments to state variables or to members of local variables of storage struct type. One cannot assign a bytes array in memory/calldata to a local bytes array storage reference. More often than not, people first read from a member of an array/mapping state variable, dataArray[i], and then write to the same member using dataArray[i] = x, which involves two slot calculations and therefore two keccak256s.
A workaround is to cast the bytes storage reference to a wrapper struct, which isn't obvious and clean. Besides, the bytecode for bytes assignment and deletion generated by solc is suboptimal.
While Solady already has BytesStorage and StringStorage, switching to a different storage layout than that of native bytes/string isn't always possible, which necessitates the current implementation.
bytes data;
bytes[] dataArray;
struct BytesWrapper {
bytes inner;
}
function f() public {
data = "Asterix";
delete data;
dataArray.push("Milady");
dataArray[0] = "Asterix";
delete dataArray[0];
bytes storage y = dataArray[0];
// Error (7407): Type literal_string "Asterix" is not implicitly convertible to expected type bytes storage pointer.
// y = "Asterix";
// Error (9767): Built-in unary operator delete cannot be applied to type bytes storage pointer.
// "delete y" is not valid, as assignments to local variables referencing storage objects
// can only be made from existing storage objects.
// https://docs.soliditylang.org/en/latest/types.html#delete
// delete y;
BytesWrapper storage bw;
assembly {
bw.slot := y.slot
}
bw.inner = "Asterix";
delete bw.inner;
}
Checklist
Ensure you completed all of the steps below before submitting your pull request:
- [x] Ran
forge fmt? - [x] Ran
forge test?
Pull requests with an incomplete checklist will be thrown out.