encoding.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import base64
  2. import string
  3. import struct
  4. from ._compat import text_type
  5. from .exc import BadData
  6. def want_bytes(s, encoding="utf-8", errors="strict"):
  7. if isinstance(s, text_type):
  8. s = s.encode(encoding, errors)
  9. return s
  10. def base64_encode(string):
  11. """Base64 encode a string of bytes or text. The resulting bytes are
  12. safe to use in URLs.
  13. """
  14. string = want_bytes(string)
  15. return base64.urlsafe_b64encode(string).rstrip(b"=")
  16. def base64_decode(string):
  17. """Base64 decode a URL-safe string of bytes or text. The result is
  18. bytes.
  19. """
  20. string = want_bytes(string, encoding="ascii", errors="ignore")
  21. string += b"=" * (-len(string) % 4)
  22. try:
  23. return base64.urlsafe_b64decode(string)
  24. except (TypeError, ValueError):
  25. raise BadData("Invalid base64-encoded data")
  26. # The alphabet used by base64.urlsafe_*
  27. _base64_alphabet = (string.ascii_letters + string.digits + "-_=").encode("ascii")
  28. _int64_struct = struct.Struct(">Q")
  29. _int_to_bytes = _int64_struct.pack
  30. _bytes_to_int = _int64_struct.unpack
  31. def int_to_bytes(num):
  32. return _int_to_bytes(num).lstrip(b"\x00")
  33. def bytes_to_int(bytestr):
  34. return _bytes_to_int(bytestr.rjust(8, b"\x00"))[0]