1"""Stage 1d: UTF-8 structural validation.
2
3Validation is decode-based: CPython's strict UTF-8 decoder enforces exactly
4the rules the old hand-rolled loop checked (overlong encodings, surrogates,
5codepoints above U+10FFFF) at C speed on every build flavor, where a per-byte
6loop runs an order of magnitude slower even compiled. See ADR-0006.
7
8The input is fed to an incremental decoder in chunks so a large input never
9allocates a matching ``str``; decoded output is discarded. ``final=False``
10reproduces the truncated-tail tolerance (an incomplete multi-byte sequence at
11the very end is fine, the input is usually a prefix of a larger whole), the
12same trick :func:`chardet._utils.decodes_without_error` uses.
13
14Note: ``from __future__ import annotations`` is intentionally omitted because
15this module is compiled with mypyc, which does not support PEP 563 string
16annotations.
17"""
18
19import codecs
20
21from chardet.pipeline import DetectionResult
22
23# Confidence curve parameters for UTF-8 detection.
24# Even a small fraction of valid multi-byte sequences is strong evidence.
25_BASE_CONFIDENCE = 0.80
26_MAX_CONFIDENCE = 0.99
27# Scale factor for the multi-byte byte ratio: mb_ratio * 6 saturates the
28# confidence ramp at ~17% multi-byte content.
29_MB_RATIO_SCALE = 6
30
31# Chunk size for incremental decoding: large enough that per-chunk overhead
32# vanishes, small enough that the transient decoded ``str`` stays negligible.
33_CHUNK_SIZE = 1 << 20
34
35# Deleting the ASCII range leaves exactly the high bytes, so
36# ``len(chunk.translate(None, _ASCII_DELETE))`` counts them at C speed.
37_ASCII_DELETE = bytes(range(0x80))
38
39_utf8_decoder = codecs.getincrementaldecoder("utf-8")
40
41# Second-byte range of the leads whose first continuation is narrower than
42# 80..BF: E0 and F0 exclude overlongs, ED excludes surrogates, F4 excludes
43# code points past U+10FFFF. Any other lead takes the full range.
44_SECOND_BYTE_RANGE: dict[int, tuple[int, int]] = {
45 0xE0: (0xA0, 0xBF),
46 0xED: (0x80, 0x9F),
47 0xF0: (0x90, 0xBF),
48 0xF4: (0x80, 0x8F),
49}
50
51
52def detect_utf8(data: bytes) -> DetectionResult | None:
53 """Validate UTF-8 byte structure.
54
55 Returns a result only if multi-byte sequences are found (pure ASCII
56 is handled by the ASCII stage).
57
58 :param data: The raw byte data to examine.
59 :returns: A :class:`DetectionResult` for UTF-8, or ``None``.
60 """
61 return scan_utf8(data)[1]
62
63
64def scan_utf8(data: bytes) -> "tuple[bool, DetectionResult | None]":
65 """Validate UTF-8 structure, separating validity from evidence.
66
67 ``None`` from :func:`detect_utf8` is two different verdicts: the data
68 is *not* UTF-8, or it is valid UTF-8 carrying no multi-byte evidence
69 (pure ASCII, ASCII plus control bytes, ASCII plus a truncated tail).
70 Only the first justifies ruling UTF-8 out downstream, so callers that
71 act on a rejection need both halves of the answer.
72
73 :param data: The raw byte data to examine.
74 :returns: ``(window_is_valid_utf8, result_or_None)``. The flag covers
75 the whole of *data*; the result is present only when complete
76 multi-byte sequences were found.
77 """
78 if not data:
79 return (True, None)
80 # Pure ASCII is valid UTF-8 with no multi-byte evidence — let the ASCII
81 # detector handle it. ``isascii`` is a single C scan and skips the
82 # decode entirely for the common all-ASCII case.
83 if data.isascii():
84 return (True, None)
85
86 length = len(data)
87 decoder = _utf8_decoder()
88 multibyte_bytes = 0
89 pending_len = 0
90 pos = 0
91 while pos < length:
92 chunk = data[pos : pos + _CHUNK_SIZE]
93 chunk_end = pos + len(chunk)
94 if pending_len == 0 and chunk.isascii():
95 # No pending sequence and no high bytes: trivially valid,
96 # nothing to count.
97 pos = chunk_end
98 continue
99 multibyte_bytes += len(chunk.translate(None, _ASCII_DELETE))
100 try:
101 decoder.decode(chunk, final=False)
102 except UnicodeError:
103 # ``final=False`` defers an incomplete final sequence that could
104 # still be completed (the caller's input is usually a prefix of a
105 # larger whole), so anything the decoder raises on is a byte no
106 # continuation can make valid, the final three included.
107 return (False, None)
108 pending_len = len(decoder.getstate()[0])
109 pos = chunk_end
110
111 # The decoder's buffered bytes are the incomplete final sequence, if
112 # any: a prefix of a sequence the data was cut through. Decoders differ
113 # on how early they reject a prefix nothing can complete — CPython
114 # defers the surrogate prefix ``ED A0`` where PyPy raises on it — so
115 # check the second byte here rather than leave the verdict to the
116 # interpreter. Then trim the tail's contribution to the counts above
117 # (at most 3 bytes).
118 if pending_len:
119 pending = decoder.getstate()[0]
120 if pending_len >= 2:
121 lo, hi = _SECOND_BYTE_RANGE.get(pending[0], (0x80, 0xBF))
122 if not lo <= pending[1] <= hi:
123 return (False, None)
124 multibyte_bytes -= pending_len
125
126 # In a validly-decoded prefix every high byte belongs to a complete
127 # multi-byte sequence, so "no complete sequences" is exactly "no high
128 # bytes outside the tail". Pure ASCII plus a truncated tail — valid,
129 # but no evidence; let the later stages handle it.
130 if multibyte_bytes == 0:
131 return (True, None)
132
133 # Confidence scales with the proportion of multi-byte bytes in the data.
134 # Even a small amount of valid multi-byte UTF-8 is strong evidence.
135 mb_ratio = multibyte_bytes / length
136 confidence_range = _MAX_CONFIDENCE - _BASE_CONFIDENCE
137 confidence = min(
138 _MAX_CONFIDENCE,
139 _BASE_CONFIDENCE + confidence_range * min(mb_ratio * _MB_RATIO_SCALE, 1.0),
140 )
141 return (
142 True,
143 DetectionResult(encoding="utf-8", confidence=confidence, language=None),
144 )