compiler.h: add offsetof() and container_of()
authorH. Peter Anvin <hpa@zytor.com>
Thu, 30 Oct 2008 17:52:08 +0000 (10:52 -0700)
committerH. Peter Anvin <hpa@zytor.com>
Thu, 30 Oct 2008 17:54:55 +0000 (10:54 -0700)
offsetof() is a C99 construct; provided here as an ersatz for older
systems.

container_of() is a nonstandard but highly useful construct, which
allows data structure control items like tree structures to be
embedded in larger data structures without the penalty of extra
pointers and allocations.

Signed-off-by: H. Peter Anvin <hpa@zytor.com>
compiler.h

index 82b0d7a..5e7e8c4 100644 (file)
@@ -1,6 +1,6 @@
 /* ----------------------------------------------------------------------- *
  *
- *   Copyright 2007 The NASM Authors - All Rights Reserved
+ *   Copyright 2007-2008 The NASM Authors - All Rights Reserved
  *
  *   This program is free software; you can redistribute it and/or modify
  *   it under the terms of the license given in the file "LICENSE"
@@ -87,6 +87,19 @@ typedef enum bool { false, true } bool;
 # endif
 #endif
 
+/* Provide a substitute for offsetof() if we don't have one.  This
+   variant works on most (but not *all*) systems... */
+#ifndef offsetof
+# define offsetof(t,m) ((size_t)&(((t *)0)->m))
+#endif
+
+/* The container_of construct: if p is a pointer to member m of
+   container class c, then return a pointer to the container of which
+   *p is a member. */
+#ifndef container_of
+# define container_of(p, c, m) ((c *)((char *)(p) - offsetof(c,m)))
+#endif
+
 /* Some misguided platforms hide the defs for these */
 #if defined(HAVE_STRCASECMP) && !HAVE_DECL_STRCASECMP
 int strcasecmp(const char *, const char *);