On 10/20/2026 8:13 PM, Philippe Mathieu-Daudé wrote: > Add a macro returning array[index] or NULL when the index is out > of bounds, useful to convert switch statements over enums into > static string lookup tables. > > Suggested-by: Pierrick Bouvier <[email protected]> > Signed-off-by: Philippe Mathieu-Daudé <[email protected]> > --- > include/qemu/osdep.h | 12 ++++++++++++ > 1 file changed, 12 insertions(+) > > diff --git a/include/qemu/osdep.h b/include/qemu/osdep.h > index 1ec5b42230b..993c8ffde0c 100644 > --- a/include/qemu/osdep.h > +++ b/include/qemu/osdep.h > @@ -533,6 +533,18 @@ void QEMU_ERROR("code path is reachable") > QEMU_BUILD_BUG_ON_ZERO(!QEMU_IS_ARRAY(x))) > #endif > > +/** > + * ARRAY_ELEM_OR_NULL() - Return an array element, or NULL if out of bounds > + * @array: array to index > + * @index: index of the element to return > + * > + * Return @array[@index] if @index is a valid index (negative indices > + * also yield NULL), otherwise return NULL. Useful to look up entries > + * in enum-indexed tables without a prior bounds check. > + */ > +#define ARRAY_ELEM_OR_NULL(array, index) \ > + ((index) < 0 || (index) >= ARRAY_SIZE(array) ? NULL : (array)[index]) > + > int qemu_daemon(int nochdir, int noclose); > void *qemu_anon_ram_alloc(size_t size, uint64_t *align, bool shared, > bool noreserve);
It assumes that array contains pointers only. If we restrict macro to char *, with a use of _Generic, it can be enforced at compile time. Another solution is to define a companion inline function that takes a const char *array[] parameter, so wrong conversion are caught at compile time also. Just a suggestion though. Reviewed-by: Pierrick Bouvier <[email protected]>
