def _strict_dns_safe_encode(name, max_length=63):
    """Will encode a username to a guaranteed-safe DNS label

    - if it contains '--' at all, jump to the end and take the hash route to avoid collisions with escaped
    - if safe, use it
    - if not, use IDNA encoding
    - if a safe encoding cannot be produced, use stripped safe characters + '--{hash}`
    - allow specifying a max_length, to give room for additional components,
      if used as only a _part_ of a DNS label.
    """
    # short-circuit: avoid accepting already-encoded results
    # which all include '--'
    if '--' in name:
        return _trim_and_hash(name)

    # if name is already safe (and can't collide with an escaped result) use it
    if _is_dns_safe(name, max_length=max_length):
        return name

    # next: use IDNA encoding, if applicable
    try:
        idna_name = idna.encode(name).decode("ascii")
    except ValueError:
        idna_name = None

    if idna_name and idna_name != name and _is_dns_safe(idna_name):
        return idna_name

    # fallback, always works: trim to safe characters and hash
    return _trim_and_hash(name)
Will encode a username to a guaranteed-safe DNS label

- if it contains '--' at all, jump to the end and take the hash route to avoid collisions with escaped
- if safe, use it
- if not, use IDNA encoding
- if a safe encoding cannot be produced, use stripped safe characters + '--{hash}`
- allow specifying a max_length, to give room for additional components,
if used as only a _part_ of a DNS label.
jupyterhub/utils.py