This overlaps with a recent commit in #3824 (f0a83fc). In think the version in that PR is nicer.