This introduces a small private API for this common pattern. The issue has been discovered thanks to Martin's huge-mem buildbot.