from typing import Optional
from typing import Union
from typing import Sequence


def _encode_sharding_dim(d: Optional[Union[str, Sequence[str], int]]) -> str:
  """Encodes the sharding annotation into a string for one dimension."""
  if d is None:
    return ''
  if isinstance(d, int):
    return 'i%d' % d
  if isinstance(d, (list, tuple)):
    return 't' + ','.join([_encode_sharding_dim(e) for e in d])

  assert isinstance(d, str)
  # The original string should not contain separators.
  assert '.' not in d
  assert ',' not in d
  assert '#' not in d
  return 's' + d