File: encoding.py

package info (click to toggle)
ansible-core 2.14.18-0%2Bdeb12u2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 29,072 kB
  • sloc: python: 172,173; cs: 4,367; sh: 3,898; makefile: 41; xml: 34
file content (38 lines) | stat: -rw-r--r-- 1,367 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Functions for encoding and decoding strings."""
from __future__ import annotations

import typing as t

ENCODING = 'utf-8'


def to_optional_bytes(value: t.Optional[t.AnyStr], errors: str = 'strict') -> t.Optional[bytes]:
    """Return the given value as bytes encoded using UTF-8 if not already bytes, or None if the value is None."""
    return None if value is None else to_bytes(value, errors)


def to_optional_text(value: t.Optional[t.AnyStr], errors: str = 'strict') -> t.Optional[str]:
    """Return the given value as text decoded using UTF-8 if not already text, or None if the value is None."""
    return None if value is None else to_text(value, errors)


def to_bytes(value: t.AnyStr, errors: str = 'strict') -> bytes:
    """Return the given value as bytes encoded using UTF-8 if not already bytes."""
    if isinstance(value, bytes):
        return value

    if isinstance(value, str):
        return value.encode(ENCODING, errors)

    raise Exception('value is not bytes or text: %s' % type(value))


def to_text(value: t.AnyStr, errors: str = 'strict') -> str:
    """Return the given value as text decoded using UTF-8 if not already text."""
    if isinstance(value, bytes):
        return value.decode(ENCODING, errors)

    if isinstance(value, str):
        return value

    raise Exception('value is not bytes or text: %s' % type(value))