MCPcopy Index your code
hub / github.com/python/cpython / encode

Method encode

Lib/encodings/idna.py:179–230  ·  view source on GitHub ↗
(self, input, errors='strict')

Source from the content-addressed store, hash-verified

177
178class Codec(codecs.Codec):
179 def encode(self, input, errors='strict'):
180
181 if errors != 'strict':
182 # IDNA is quite clear that implementations must be strict
183 raise UnicodeError(f"Unsupported error handling: {errors}")
184
185 if not input:
186 return b'', 0
187
188 try:
189 result = input.encode('ascii')
190 except UnicodeEncodeError:
191 pass
192 else:
193 # ASCII name: fast path
194 labels = result.split(b'.')
195 for i, label in enumerate(labels[:-1]):
196 if len(label) == 0:
197 offset = sum(len(l) for l in labels[:i]) + i
198 raise UnicodeEncodeError("idna", input, offset, offset+1,
199 "label empty")
200 for i, label in enumerate(labels):
201 if len(label) >= 64:
202 offset = sum(len(l) for l in labels[:i]) + i
203 raise UnicodeEncodeError("idna", input, offset, offset+len(label),
204 "label too long")
205 return result, len(input)
206
207 result = bytearray()
208 labels = dots.split(input)
209 if labels and not labels[-1]:
210 trailing_dot = b'.'
211 del labels[-1]
212 else:
213 trailing_dot = b''
214 for i, label in enumerate(labels):
215 if result:
216 # Join with U+002E
217 result.extend(b'.')
218 try:
219 result.extend(ToASCII(label))
220 except (UnicodeEncodeError, UnicodeDecodeError) as exc:
221 offset = sum(len(l) for l in labels[:i]) + i
222 raise UnicodeEncodeError(
223 "idna",
224 input,
225 offset + exc.start,
226 offset + exc.end,
227 exc.reason,
228 )
229 result += trailing_dot
230 return result.take_bytes(), len(input)
231
232 def decode(self, input, errors='strict'):
233

Callers 3

ToASCIIFunction · 0.45
ToUnicodeFunction · 0.45
_buffer_decodeMethod · 0.45

Calls 5

enumerateFunction · 0.85
ToASCIIFunction · 0.85
take_bytesMethod · 0.80
splitMethod · 0.45
extendMethod · 0.45

Tested by

no test coverage detected