]>
jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/itsdangerous/encoding.py
6 from .exc
import BadData
8 _t_str_bytes
= _t
.Union
[str, bytes]
12 s
: _t_str_bytes
, encoding
: str = "utf-8", errors
: str = "strict"
14 if isinstance(s
, str):
15 s
= s
.encode(encoding
, errors
)
20 def base64_encode(string
: _t_str_bytes
) -> bytes:
21 """Base64 encode a string of bytes or text. The resulting bytes are
24 string
= want_bytes(string
)
25 return base64
.urlsafe_b64encode(string
).rstrip(b
"=")
28 def base64_decode(string
: _t_str_bytes
) -> bytes:
29 """Base64 decode a URL-safe string of bytes or text. The result is
32 string
= want_bytes(string
, encoding
="ascii", errors
="ignore")
33 string
+= b
"=" * (-len(string
) % 4)
36 return base64
.urlsafe_b64decode(string
)
37 except (TypeError, ValueError) as e
:
38 raise BadData("Invalid base64-encoded data") from e
41 # The alphabet used by base64.urlsafe_*
42 _base64_alphabet
= f
"{string.ascii_letters}{string.digits}-_=".encode("ascii")
44 _int64_struct
= struct
.Struct(">Q")
45 _int_to_bytes
= _int64_struct
.pack
46 _bytes_to_int
= _t
.cast("_t.Callable[[bytes], _t.Tuple[int]]", _int64_struct
.unpack
)
49 def int_to_bytes(num
: int) -> bytes:
50 return _int_to_bytes(num
).lstrip(b
"\x00")
53 def bytes_to_int(bytestr
: bytes) -> int:
54 return _bytes_to_int(bytestr
.rjust(8, b
"\x00"))[0]