0

I have the following structure and want to compute its hash:

struct SomeStruct {
    uint8 field1;
    int24 field2;
    uint256 field3;
}

I was expecting that due to packing the size of this structure is 64 bytes, as the first two fields fit in a single 32-byte slot. However I tested it with this code:

SomeStruct memory s = SomeStruct(0x13, 0x567890, type(uint256).max - 100000000000);
bytes32 h1 = keccak256(abi.encode(s));
bytes32 h2;
assembly("memory-safe") {
    h2 := keccak256(s, mul(32, 3))
}

After this, both hashes h1 and h2 are equal. Does packing only apply to structs in storage rather than structs in other memory types?

1 Answer 1

1

Does packing only apply to structs in storage rather than structs in other memory types?

Yes. From the Solidity docs' Layout of State Variables in Storage:

It might be beneficial to use reduced-size types if you are dealing with storage values because the compiler will pack multiple elements into one storage slot, and thus, combine multiple reads or writes into a single operation. [...]

When dealing with function arguments or memory values, there is no inherent benefit because the compiler does not pack these values.

The article Layout in Memory has an example for struct:

The following struct occupies 96 bytes (3 slots of 32 bytes) in storage, but 128 bytes (4 items with 32 bytes each) in memory.

struct S {
    uint a;
    uint b;
    uint8 c;
    uint8 d;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.