named-data-iot / ndn-lite

A lightweight NDN protocol stack with high-level application support including security bootstrapping, access control, trust management, etc.
https://ndn-lite.named-data.net
GNU Lesser General Public License v3.0
44 stars 16 forks source link

Wasted memory in ndn_metainfo_t #34

Closed yoursunny closed 5 years ago

yoursunny commented 5 years ago

As of 513e020a28cc76ac12ee4cdb3bdaf8ebcb13428c, ndn_metainfo_t type is declared as:

typedef struct ndn_metainfo {
  uint8_t content_type;
  uint32_t freshness_period;
  name_component_t final_block_id;
  uint8_t enable_ContentType;
  uint8_t enable_FreshnessPeriod;
  uint8_t enable_FinalBlockId;
} ndn_metainfo_t;

Due to memory alignment rules, the compiler inserts a 3-byte padding before freshness_period field. This struct would consume 55 bytes of memory (name_component_t has 44 bytes).

A better arrangement is:

typedef struct ndn_metainfo {
  uint32_t freshness_period;
  name_component_t final_block_id;
  uint8_t content_type;
  uint8_t enable_ContentType;
  uint8_t enable_FreshnessPeriod;
  uint8_t enable_FinalBlockId;
} ndn_metainfo_t;

It needs 52 bytes of memory, fewer than the previous layout.

Pesa commented 5 years ago

If you want to save even more space, the uint8_t enable_* fields, that are used as boolean flags, can be grouped in a single bitfield.

yoursunny commented 5 years ago

the uint8t enable* fields, that are used as boolean flags, can be grouped in a single bitfield.

Moreover, they can be packed into high bits of FreshnessPeriod. 24 bits are enough for FreshnessPeriod.