Attached is another revision of this patch with the new helper function you suggested. Is this version okay to commit?
I don't actually have the ability to grant check-in in this area. I just figured that implementing some of these suggestions might make it more palatable to reviewers who do.
The patch is much better, but IMO it is a bit hard to read and not generic enough, but I defer to the relevant maintainers.
Aldy