FireBot/overrides.py

55 lines
1.7 KiB
Python
Raw Normal View History

2023-11-05 01:37:35 +00:00
#!/usr/bin/python3
from builtins import bytes as bbytes
from typing import TypeVar, Type, Any
_T = TypeVar("_T")
2023-11-15 22:34:12 +00:00
bbytes = bbytes
2023-11-05 01:37:35 +00:00
2023-11-21 02:18:48 +00:00
2023-11-05 01:37:35 +00:00
class bytes(bbytes):
"""Local override of builtin bytes class to add "lazy_decode"
2023-11-08 03:23:59 +00:00
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
2023-11-08 03:23:59 +00:00
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
"""
2023-11-05 01:37:35 +00:00
def __new__(
cls: Type[_T],
thing: Any = None,
encoding: str = "UTF-8",
errors: str = "strict",
) -> _T:
if type(thing) == str:
2023-11-09 21:37:08 +00:00
cls.value = super().__new__(cls, thing, encoding, errors) # type: ignore
2023-11-05 01:37:35 +00:00
elif thing == None:
2023-11-09 21:37:08 +00:00
cls.value = super().__new__(cls) # type: ignore
2023-11-05 01:37:35 +00:00
elif thing != None:
2023-11-09 21:37:08 +00:00
cls.value = super().__new__(cls, thing) # type: ignore
2023-11-05 01:37:35 +00:00
else:
2023-11-09 03:20:50 +00:00
raise AttributeError("This shouldn't happen")
2023-11-09 21:37:08 +00:00
return cls.value # type: ignore
2023-11-05 01:37:35 +00:00
@classmethod
2023-11-14 22:18:41 +00:00
def lazy_decode(cls) -> str:
2023-11-14 22:09:38 +00:00
"Lazily decode the bytes object using string manipulation"
2023-11-09 03:41:07 +00:00
return str(cls.value)[2:-1]
2023-11-14 22:09:38 +00:00
@classmethod
2023-11-14 22:18:16 +00:00
def safe_decode(cls) -> str:
2023-11-15 00:03:09 +00:00
'Calls cls.decode(cls, errors = "ignore"), if that errors, returns a blank string'
2023-11-14 22:16:39 +00:00
try:
2023-11-15 05:26:02 +00:00
return cls.decode(cls.value, errors="ignore") # type: ignore
2023-11-14 22:16:39 +00:00
except TypeError:
2023-11-15 00:37:46 +00:00
print("panik - invalid UTF-8")
return "nul"