util.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # -*- coding: utf-8 -*-
  2. """
  3. hyper/common/util
  4. ~~~~~~~~~~~~~~~~~
  5. General utility functions for use with hyper.
  6. """
  7. from hyper.compat import unicode, bytes, imap
  8. from ..packages.rfc3986.uri import URIReference
  9. from ..compat import is_py3
  10. def to_bytestring(element):
  11. """
  12. Converts a single string to a bytestring, encoding via UTF-8 if needed.
  13. """
  14. if isinstance(element, unicode):
  15. return element.encode('utf-8')
  16. elif isinstance(element, bytes):
  17. return element
  18. else:
  19. raise ValueError("Non string type.")
  20. def to_bytestring_tuple(*x):
  21. """
  22. Converts the given strings to a bytestring if necessary, returning a
  23. tuple. Uses ``to_bytestring``.
  24. """
  25. return tuple(imap(to_bytestring, x))
  26. def to_host_port_tuple(host_port_str, default_port=80):
  27. """
  28. Converts the given string containing a host and possibly a port
  29. to a tuple.
  30. """
  31. uri = URIReference(
  32. scheme=None,
  33. authority=host_port_str,
  34. path=None,
  35. query=None,
  36. fragment=None
  37. )
  38. host = uri.host.strip('[]')
  39. if not uri.port:
  40. port = default_port
  41. else:
  42. port = int(uri.port)
  43. return (host, port)
  44. def to_native_string(string, encoding='utf-8'):
  45. if isinstance(string, str):
  46. return string
  47. return string.decode(encoding) if is_py3 else string.encode(encoding)