Get sum of sizes of struct members

I have a use case where I want to get the sum of the sizes of the struct's members in bytes.
Due to alignment, std::mem::size_of() is not an option.
I.e. I am looking for a function like accumulated_size<T>():

struct Data {
    header: u8,
    payload: u128,
}

accumulated_size::<Data>() // == 17

Is there something in the standard library, that I'm missing or some de-facto standard crate for this?
I do not need or want to use #[repr(packed)] btw.

    std::mem::size_of::<Data>;

Edit: Oh schute, I just realized, that my suggestion was excluded. :frowning:
HTH

And do what with it?

Allocate a buffer of appropriate size.

I came across this problem when I wanted to use read_exact to take bytes from a stream, so interested to see other answers.

Using the bin_rw crate I was able to do it. Not sure if this is totally correct or best way as I'm still learning Rust but it worked for me.

Something like this:

use binrw::io::Cursor;
use binrw::{BinRead, BinResult, BinWrite, BinWriterExt};

fn main() {
    let size = Data::view_size().inspect_err(|e| eprintln!("{e:?}")).unwrap();
    assert_eq!(size, 17);
}

#[derive(BinRead, BinWrite, Debug, Default)]
pub struct Data {
    pub header: u8,
    pub data: u128,
}

impl Data {
    pub fn view_size() -> BinResult<usize> {
        let mut buf = Cursor::new(vec![]);
        buf.write_le(&Self::default())?;
        Ok(buf.into_inner().len())
    }
}

I had a similar use case for which I wrote le-stream and le-stream-derive.
However, my current use case needs to buffer data instead of streaming it, so I need to know the size at compile time.
I now quickly scrabbled my own implementations: buf_sized and buf_sized_derive

I guess I'm confused what "appropriate" means, then. Maybe you're actually looking for something packed you can zerocopy inside said buffer?

It sounds like they need to know the number of bytes to read, not just the amount to allocate. In other words, the stream data isn't self-describing.

1 Like

Indeed. I do not want #[repr(packed)] since the software will be used on a wonky ARM device, and I don't want the structures to cause UB when loaded into memory. I just need the size for when writing bytes into a buffer which then later will be written to a serial port.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.