I am pretty sure we already have something like this in bson.c where we also need to check a similar thing to figure out whether we need to store a BSON object or BSON array. If not, those two implementations should use the same C function.