Re: [PATCH 2/6] list: add new MACROs to make iterator invisiable

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, Mar 10, 2022 at 04:46:33PM -0800, Linus Torvalds wrote:
> On Thu, Mar 10, 2022 at 3:54 PM Michał Mirosław <mirq-linux@xxxxxxxxxxxx> wrote:
> >
> > If the macro implementation doesn't have to be pretty, maybe it could go
> > a step further and remember the list_head's offset? That would look
> > something like following (expanding on your patch; not compile tested):
> 
> Oh, I thought of it.
> 
> It gets complicated.
[...]

It seems that it's not that bad if we don't require checking whether
a list_head of an entry is only ever used with a single list parent. The
source type is not needed for the macros, and it turns out that pre-declaring
the offset type is also not needed.

I compile-tested the code below on godbolt.org with -std=c11:

struct list_head {
	struct list_head *prev, *next;
};

#define offsetof __builtin_offsetof
#define typeof __typeof

#define list_traversal_head(name,type,target_member) \
	union { \
		struct list_head name; \
		type *name##_traversal_type; \
		char (*name##_list_head_offset)[offsetof(type, target_member)];  \
	}

#define self_list_ref_offset_type(type,target_member) \
	type##__##target_member##__offset__

#define define_self_list_ref_offset(type,target_member) \
	self_list_ref_offset_type(type,target_member) \
	{ char ignoreme__[offsetof(type, target_member)]; }

#define self_list_traversal_head(name,type,target_member) \
	union { \
		struct list_head name; \
		type *name##_traversal_type; \
		self_list_ref_offset_type(type,target_member) *name##_list_head_offset;  \
	}

#define list_traversal_entry(ptr, head) \
	(typeof(*head##_traversal_type))((void *)ptr - sizeof(**head##_list_head_offset))

#define list_traversal_entry_head(ptr, head) \
	((struct list_head *)((void *)ptr + sizeof(**head##_list_head_offset)))

#define list_traversal_entry_is_head(ptr, head) \
	(list_traversal_entry_head(ptr, head) == (head))

#define list_traversal_next_entry(ptr, head) \
	list_traversal_entry(list_traversal_entry_head(ptr, head)->next, head)

#define list_traverse(pos, head) \
    for (typeof(*head##_traversal_type) pos = list_traversal_entry((head)->next, head); \
    !list_traversal_entry_is_head(pos, head); \
    pos = list_traversal_next_entry(pos,head))

struct entry {
    self_list_traversal_head(self_list, struct entry, child_head);
    struct list_head child_head;
};

define_self_list_ref_offset(struct entry, child_head);


void bar(struct entry *b);

void foo(struct entry *a)
{
    list_traverse(pos, &a->self_list) {
        bar(pos);
    }
}

-- 
Michał Mirosław



[Index of Archives]     [Linux&nblp;USB Development]     [Linux Media]     [Video for Linux]     [Linux Audio Users]     [Yosemite Secrets]     [Linux Kernel]     [Linux SCSI]

  Powered by Linux