3

As the title states, which method is recommended to calculate the size

assuming types are non -zero copy hence alignment calculation is not needed or is the type aligned per say

in this situation which method is preferred and why ? i have seen people saying to not use sizeof i dont understand what is the harm in it except for paying rent for a few more bytes.

Update : mem::sizeof also takes into account the padding done to align the struct, if so manually calculating the individual sizes and summing it up is wrong is it not ? but almost every program i read seems to do it manually if so why is it not necessary to take into account the padding added while coming up with the final size

further question :Also if i have type like Option how is the size calculated ? 1 for Option + 1 for Enum +1 if it has simple fields ? or the 1 allocated for Enum Covers it ?

5
  • i am aware rust uses null pointer optimization but if my account struct does not have any types like Option or Enum, mem::sizeof should work fine right ? ref : Commented Jul 26, 2022 at 16:25
  • Also if i have type like Option<Enum with simple fields> how is the size calculated ? 1 for Option + 1 for Enum +1 if it has simple fields ? or the 1 allocated for Enum Covers it ? Commented Jul 26, 2022 at 16:26
  • If you have additional questions these should be added to the question itself or moved to a new question
    – Henry E
    Commented Jul 27, 2022 at 20:01
  • done added it to the question Commented Jul 28, 2022 at 8:53
  • Reading it more carefully now, this does seem like worth asking in a separate question perhaps
    – Henry E
    Commented Jul 28, 2022 at 10:07

1 Answer 1

3

For zero_copy accounts, you can use mem::size_of(). But for non-zero_copy accounts, the alignment is off and size_of() will give you a larger, incorrect space value. Instead you can do

    let acc = Account::default();
    let size = x.try_to_vec().unwrap().len();`

Basically, you cannot use the mem::size_of for serialized accounts, you need to give the serialized size, which can be inferred from the Default trait of the account

3
  • i think it would be wrong to say alignment is off, i think if am not wrong the way to think about it is, not to think about alignment if its not zero-copy but think in terms of how borsh will serialize it, which is independent of the alignment, is my observation correct ser ? Commented Jul 26, 2022 at 23:49
  • yes, exactly, it depends on how borsh will serialize it
    – hrs8
    Commented Jul 27, 2022 at 7:18
  • Can this method just be run once at compile time or will this code run every time you want to initialize an account with the correct amount of space?
    – Henry E
    Commented Jul 27, 2022 at 19:58

Your Answer

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

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