Functional Weave
Code in TypeScript

encoding.utf8@1.0.0

impl/python/utf8_decode.py

906 bytes · the Python implementation · view raw

import builtins
from typing import Sequence


def utf8_decode(bytes: Sequence[int]) -> str:
    """UTF-8 bytes back to text, strictly (RFC 3629).

    Python's own decoder is already strict about overlong forms, surrogates
    and code points past U+10FFFF, and the plain "utf-8" codec keeps a leading
    byte order mark, so once the byte values are checked it does the work.
    (The parameter is named by the manifest, hence builtins.bytes.)
    """
    if isinstance(bytes, (str, dict)) or not hasattr(bytes, "__len__"):
        raise TypeError("bytes must be a list of integers from 0 to 255")
    for b in bytes:
        if type(b) is not int or b < 0 or b > 255:
            raise ValueError("bytes must be a list of integers from 0 to 255")
    try:
        return builtins.bytes(bytes).decode("utf-8")
    except UnicodeDecodeError:
        raise ValueError("bytes are not valid UTF-8") from None