pfr icon indicating copy to clipboard operation
pfr copied to clipboard

Get structure padding

Open NN--- opened this issue 4 years ago • 8 comments
trafficstars

Is it possible to calculate structure padding using this library ?

NN--- avatar Sep 04 '21 08:09 NN---

Yes. sizeof(your_structure) - sizeof(all fields), iterate over the fields using this library. Or do you mean alignment? Than just use alignof

apolukhin avatar Sep 10 '21 16:09 apolukhin

I mean to have a predefined constexpr function in the library.

NN--- avatar Sep 10 '21 16:09 NN---

I'm still not shure what do you want to get. Please, provide a sample implementation of such function.

apolukhin avatar Sep 12 '21 14:09 apolukhin

template<typename T>
void f(T&& value)
{
static constexpr size_t padding = get_padding<T>();
if constexpr (padding > 8){
 Do this
}
else{
 Do that 
}
}

NN--- avatar Sep 12 '21 15:09 NN---

I need a more usable example to understand what are the use-cases and what API suits those cases best. For what do you need the padding and how are you planning to use it?

apolukhin avatar Sep 29 '21 09:09 apolukhin

My intent was to automatically detect structure padding and use it for memory optimization if there is a padding. For instance optional<MyStruct> doesn't need to waste additional 8 bytes for a single boolean.

NN--- avatar Sep 29 '21 09:09 NN---

I think you can use something like this

template<typename T>
consteval bool get_padding() {
    namespace hana = boost::hana;

    auto field_size = [](auto i) {
        return sizeof(boost::pfr::get<i>(std::declval<T>()));
    };

    constexpr size_t count = boost::pfr::tuple_size_v<T>;
    auto range = hana::make_range(hana::int_c<0>, hana::int_c<count>);

    constexpr size_t result = hana::unpack(range, [=](auto... is) {
        return (0 + ... + field_size(is));
    });
    return sizeof(T) - result;
}

technic avatar Nov 09 '21 22:11 technic

@technic I see that I was not clear in the original request. This approach does calculates the padding but it doesn't say where the padding is. For instance given

struct A{
  int a;
  char b;
  int c;
  chat d;
  int e;
};

The padding could be 6 bytes in the middle and 0 bytes in the end.

My original intent is to use this padding for internal purposes to reduce memory usage.

Thanks.

NN--- avatar Mar 12 '22 11:03 NN---