An optimized version of this function already exists in forge.util. When I merge in this pull request I'll reuse it.