Debian Codegraph @

idna/codec.py

raw
1 from __future__ import annotations
2
3 import codecs
4 from typing import Any
5
6 from .core import IDNAError, _unicode_dots_re, alabel, decode, encode, ulabel
7
8
9 class Codec(codecs.Codec):
10 """Stateless IDNA 2008 codec.
11
12 Implements the :class:`codecs.Codec` protocol so that the whole-domain
13 encoder (:func:`idna.encode`) and decoder (:func:`idna.decode`) are
14 accessible through the standard codec machinery as ``"idna2008"``.
15
16 Only the ``"strict"`` error handler is supported; any other handler
17 raises :exc:`~idna.IDNAError`.
18 """
19
20 def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]: # ty: ignore[invalid-method-override]
21 if errors != "strict":
22 raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors")
23
24 if not data:
25 return b"", 0
26
27 return encode(data), len(data)
28
29 def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]: # ty: ignore[invalid-method-override]
30 if errors != "strict":
31 raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors")
32
33 if not data:
34 return "", 0
35
36 return decode(data), len(data)
37
38
39 class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
40 """Incremental IDNA 2008 encoder.
41
42 Buffers a partial trailing label across calls until either the next
43 label separator is seen or ``final=True``, so that streamed input is
44 encoded one whole label at a time. Any of the four Unicode label
45 separators (``U+002E``, ``U+3002``, ``U+FF0E``, ``U+FF61``) ends a
46 label; the result always uses ``U+002E`` as the separator.
47
48 Only the ``"strict"`` error handler is supported.
49 """
50
51 def _buffer_encode(self, data: str, errors: str, final: bool) -> tuple[bytes, int]: # ty: ignore[invalid-method-override]
52 if errors != "strict":
53 raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors")
54
55 if not data:
56 return b"", 0
57
58 labels = _unicode_dots_re.split(data)
59 trailing_dot = b""
60 if labels:
61 if not labels[-1]:
62 trailing_dot = b"."
63 del labels[-1]
64 elif not final:
65 # Keep potentially unfinished label until the next call
66 del labels[-1]
67 if labels:
68 trailing_dot = b"."
69
70 result = []
71 size = 0
72 for label in labels:
73 result.append(alabel(label))
74 if size:
75 size += 1
76 size += len(label)
77
78 result_bytes = b".".join(result) + trailing_dot
79 size += len(trailing_dot)
80 return result_bytes, size
81
82
83 class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
84 """Incremental IDNA 2008 decoder.
85
86 Buffers a partial trailing label across calls until either the next
87 label separator is seen or ``final=True``, so that streamed input is
88 decoded one whole label at a time.
89
90 Only the ``"strict"`` error handler is supported.
91 """
92
93 def _buffer_decode(self, data: Any, errors: str, final: bool) -> tuple[str, int]: # ty: ignore[invalid-method-override]
94 if errors != "strict":
95 raise IDNAError(f'Unsupported error handling "{errors}"', code="unsupported_errors")
96
97 if not data:
98 return ("", 0)
99
100 if not isinstance(data, str):
101 try:
102 data = str(data, "ascii")
103 except UnicodeDecodeError as err:
104 raise IDNAError("Invalid ASCII in A-label", code="invalid_ascii") from err
105
106 labels = _unicode_dots_re.split(data)
107 trailing_dot = ""
108 if labels:
109 if not labels[-1]:
110 trailing_dot = "."
111 del labels[-1]
112 elif not final:
113 # Keep potentially unfinished label until the next call
114 del labels[-1]
115 if labels:
116 trailing_dot = "."
117
118 result = []
119 size = 0
120 for label in labels:
121 result.append(ulabel(label))
122 if size:
123 size += 1
124 size += len(label)
125
126 result_str = ".".join(result) + trailing_dot
127 size += len(trailing_dot)
128 return (result_str, size)
129
130
131 class StreamWriter(Codec, codecs.StreamWriter):
132 pass
133
134
135 class StreamReader(Codec, codecs.StreamReader):
136 pass
137
138
139 def search_function(name: str) -> codecs.CodecInfo | None:
140 """Codec search function registered with :mod:`codecs`.
141
142 Returns a :class:`codecs.CodecInfo` for the ``"idna2008"`` codec name
143 so that ``str.encode("idna2008")`` and ``bytes.decode("idna2008")``
144 invoke the IDNA 2008 codec defined in this module.
145
146 :param name: The codec name being looked up.
147 :returns: A :class:`codecs.CodecInfo` instance if ``name`` is
148 ``"idna2008"``, otherwise ``None``.
149 """
150 if name != "idna2008":
151 return None
152 return codecs.CodecInfo(
153 name=name,
154 encode=Codec().encode,
155 decode=Codec().decode, # type: ignore
156 incrementalencoder=IncrementalEncoder,
157 incrementaldecoder=IncrementalDecoder,
158 streamwriter=StreamWriter,
159 streamreader=StreamReader,
160 )
161
162
163 codecs.register(search_function)