Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type-checking container_of macro #25

Merged
merged 1 commit into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions eventrouter/internal/defs.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
#define ER_UNUSED(statement) (void)(statement);

/// Returns the address of the structure containing the member.
#ifndef container_of
#define container_of(ptr, type, member) \

/// The "?:" conditional operator requires its second and third operands to
/// be of compatible type, so by writing "1 ? (ptr) : &((type *)0)->member"
/// instead of simply writing "(ptr)", we ensure that `ptr` actually does
/// point to a type compatible with `member` (compilation halts if it doesn't).

#define er_container_of(ptr, type, member) \
({ \
const typeof(((type *)0)->member) *__mptr = (ptr); \
void *__mptr = (1 ? (ptr) : &((type *)0)->member); \
(type *)((char *)__mptr - offsetof(type, member)); \
})
#endif

#endif /* EVENTROUTER_DEFS_H */
2 changes: 1 addition & 1 deletion eventrouter/internal/event.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ extern "C"
/// `a_event_p`. The developer must ensure that `a_type` is correct. This
/// macro returns the surrounding struct by value instead of by reference.
#define FROM_ER_EVENT(a_event_p, a_type) \
(*container_of(a_event_p, a_type, ER_EVENT_MEMBER))
(*er_container_of(a_event_p, a_type, ER_EVENT_MEMBER))

/// Initialize the event fields of a struct which mixes-in `ErEvent_t`
/// behavior. This differs from `ErEventInit_t` in that it can be used in
Expand Down
2 changes: 1 addition & 1 deletion eventrouter/internal/eventrouter_baremetal.c
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ ErEvent_t *ErGetEventToDeliver(void)
ErList_t *node = &s_context.m_events.m_deliver_now;
if (node->m_next != NULL)
{
ret = container_of(node->m_next, ErEvent_t, m_next);
ret = er_container_of(node->m_next, ErEvent_t, m_next);
node->m_next = node->m_next->m_next;
ret->m_next.m_next = NULL;
}
Expand Down
Loading