Encode strings to bytes-like and decode bytes-like to strings
| 2 | |
| 3 | |
| 4 | class Encoder: |
| 5 | "Encode strings to bytes-like and decode bytes-like to strings" |
| 6 | |
| 7 | __slots__ = "encoding", "encoding_errors", "decode_responses" |
| 8 | |
| 9 | def __init__(self, encoding, encoding_errors, decode_responses): |
| 10 | self.encoding = encoding |
| 11 | self.encoding_errors = encoding_errors |
| 12 | self.decode_responses = decode_responses |
| 13 | |
| 14 | def encode(self, value): |
| 15 | "Return a bytestring or bytes-like representation of the value" |
| 16 | if isinstance(value, (bytes, bytearray, memoryview)): |
| 17 | return value |
| 18 | elif isinstance(value, bool): |
| 19 | # special case bool since it is a subclass of int |
| 20 | raise DataError( |
| 21 | "Invalid input of type: 'bool'. Convert to a " |
| 22 | "bytes, string, int or float first." |
| 23 | ) |
| 24 | elif isinstance(value, (int, float)): |
| 25 | value = repr(value).encode() |
| 26 | elif not isinstance(value, str): |
| 27 | # a value we don't know how to deal with. throw an error |
| 28 | typename = type(value).__name__ |
| 29 | raise DataError( |
| 30 | f"Invalid input of type: '{typename}'. " |
| 31 | f"Convert to a bytes, string, int or float first." |
| 32 | ) |
| 33 | if isinstance(value, str): |
| 34 | value = value.encode(self.encoding, self.encoding_errors) |
| 35 | return value |
| 36 | |
| 37 | def decode(self, value, force=False): |
| 38 | "Return a unicode string from the bytes-like representation" |
| 39 | if self.decode_responses or force: |
| 40 | if isinstance(value, memoryview): |
| 41 | value = value.tobytes() |
| 42 | if isinstance(value, bytes): |
| 43 | value = value.decode(self.encoding, self.encoding_errors) |
| 44 | return value |
no outgoing calls