Debian Codegraph @

test/lib/ansible_test/_internal/encoding.py

raw
1 """Functions for encoding and decoding strings."""
2
3 from __future__ import annotations
4
5 import typing as t
6
7 ENCODING = 'utf-8'
8
9
10 def to_optional_bytes(value: t.Optional[str | bytes], errors: str = 'strict') -> t.Optional[bytes]:
11 """Return the given value as bytes encoded using UTF-8 if not already bytes, or None if the value is None."""
12 return None if value is None else to_bytes(value, errors)
13
14
15 def to_optional_text(value: t.Optional[str | bytes], errors: str = 'strict') -> t.Optional[str]:
16 """Return the given value as text decoded using UTF-8 if not already text, or None if the value is None."""
17 return None if value is None else to_text(value, errors)
18
19
20 def to_bytes(value: str | bytes, errors: str = 'strict') -> bytes:
21 """Return the given value as bytes encoded using UTF-8 if not already bytes."""
22 if isinstance(value, bytes):
23 return value
24
25 if isinstance(value, str):
26 return value.encode(ENCODING, errors)
27
28 raise Exception('value is not bytes or text: %s' % type(value))
29
30
31 def to_text(value: str | bytes, errors: str = 'strict') -> str:
32 """Return the given value as text decoded using UTF-8 if not already text."""
33 if isinstance(value, bytes):
34 return value.decode(ENCODING, errors)
35
36 if isinstance(value, str):
37 return value
38
39 raise Exception('value is not bytes or text: %s' % type(value))