def _get_top_level_type_desc(cls):
  """
  Returns the protobuf descriptor for the top-level parent of 'cls'.

  If 'cls' is itself top-level, then returns 'cls.DESCRIPTOR'.

  NB: This is essentially identical to
  'google.protobuf.descriptor._NestedDescriptorBase.GetTopLevelContainingType'.
  However, that method was removed as of 3.1.0, while the 'containing_type'
  attribute remains compatible with proto3.
  """
  curr_desc = cls.DESCRIPTOR
  while curr_desc.containing_type:
    curr_desc = curr_desc.containing_type
  return curr_desc