from typing import Generic, TypeVar class UnwrapException(Exception): def __init__(self, *args: object) -> None: super().__init__(*args) T = TypeVar("T") E = TypeVar("E") class Result(Generic[T, E]): def __init__(self) -> None: super().__init__() def ok(self) -> bool: raise NotImplementedError() def value(self) -> T: raise NotImplementedError() def error(self) -> E: raise NotImplementedError() class Ok(Result[T, E]): def __init__(self, value: T) -> None: super().__init__() self.__value = value def ok(self) -> bool: return True def value(self) -> T: return self.__value def error(self) -> E: raise UnwrapException("cannot unwrap error of ok result") class Err(Result[T, E]): def __init__(self, error: E) -> None: super().__init__() self.__error = error def ok(self) -> bool: return False def value(self) -> T: raise UnwrapException("cannot unwrap value of error result") def error(self) -> E: return self.__error def unescape_string(value: str) -> Result[str, str]: result = "" i = 0 while i < len(value): if value[i] == "\\": i += 1 if i >= len(value): return Err("unescaped '\\'") elif value[i] == "0": result += "\0" elif value[i] == "n": result += "\n" elif value[i] == "t": result += "\t" elif value[i] == "r": result += "\r" else: result += value[i] else: result += value[i] i += 1 return Ok(result) def escape_string(value: str) -> str: result = "" for char in value: if char == "\0": result += "\\0" elif char == "\n": result += "\\n" elif char == "\t": result += "\\t" elif char == "\r": result += "\\r" elif char == "\"": result += "\\\"" elif char == "\'": result += "\\'" elif char == "\\": result += "\\\\" else: result += char return result