def _get_object_size(data, position, obj_end):
    """Validate and return a BSON document's size."""
    try:
        obj_size = _UNPACK_INT(data[position:position + 4])[0]
    except struct.error as exc:
        raise InvalidBSON(str(exc))
    end = position + obj_size - 1
    if data[end:end + 1] != b"\x00":
        raise InvalidBSON("bad eoo")
    if end >= obj_end:
        raise InvalidBSON("invalid object length")
    # If this is the top-level document, validate the total size too.
    if position == 0 and obj_size != obj_end:
        raise InvalidBSON("invalid object length")
    return obj_size, end
Validate and return a BSON document's size.