Backport changes from bson branch.