pythonrs 0.1.4

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The `_codecs` C-accelerator module: the codec registry (`register`,
//! `lookup`, `register_error`, `lookup_error`), the generic `encode`/`decode`
//! entry points, and the natively-implemented codecs.
//!
//! PORTED from RustPython's `crates/vm/src/stdlib/_codecs.rs`
//! (<https://github.com/RustPython/RustPython>, MIT licence), including its
//! division of labour: utf-8, latin-1, ascii and the utf-16/32 family are
//! implemented natively because they are the ones that matter for startup and
//! I/O, while the long tail (utf-7, the charmap-driven single-byte codecs, the
//! escape codecs) is left to the pure-Python `encodings` package that the
//! registry finds anyway. The fast paths are theirs too: an all-ASCII string
//! encodes to latin-1/ascii by handing back its own bytes, and a str that is
//! already valid utf-8 encodes to utf-8 the same way.
//!
//! The error handlers follow CPython's contract — `strict` raises,
//! `ignore` drops, `replace` substitutes U+FFFD on decode and `?` on encode,
//! `backslashreplace`/`xmlcharrefreplace` escape, `surrogateescape` maps
//! undecodable bytes to U+DC80..U+DCFF and back.
//!
//! Wiring (done by the parent): an `import_module` arm for `"_codecs"` calling
//! [`entries`], and a `call_builtin_function` arm routing `_codecs.*` to
//! [`call`].

use crate::host::{self, PyHost, PyObj};
use fusevm::Value;

/// How an encode/decode error is handled. Anything not in this set is looked up
/// in the user registry by `lookup_error`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Errors {
    Strict,
    Ignore,
    Replace,
    BackslashReplace,
    XmlCharRefReplace,
    SurrogateEscape,
    SurrogatePass,
}

impl Errors {
    fn parse(s: &str) -> Self {
        match s {
            "ignore" => Self::Ignore,
            "replace" => Self::Replace,
            "backslashreplace" => Self::BackslashReplace,
            "xmlcharrefreplace" => Self::XmlCharRefReplace,
            "surrogateescape" => Self::SurrogateEscape,
            "surrogatepass" => Self::SurrogatePass,
            _ => Self::Strict,
        }
    }
}

fn enc_err(enc: &str, pos: usize, ch: char) -> String {
    format!(
        "UnicodeEncodeError: '{enc}' codec can't encode character '\\u{:04x}' in position {pos}",
        ch as u32
    )
}

fn dec_err(enc: &str, pos: usize, why: &str) -> String {
    format!("UnicodeDecodeError: '{enc}' codec can't decode byte in position {pos}: {why}")
}

/// Encode `s` to a single-byte codec whose repertoire is `0..=limit`.
fn encode_single_byte(enc: &str, s: &str, limit: u32, errors: Errors) -> Result<Vec<u8>, String> {
    let mut out = Vec::with_capacity(s.len());
    for (i, c) in s.chars().enumerate() {
        let cp = c as u32;
        if cp <= limit {
            out.push(cp as u8);
            continue;
        }
        match errors {
            Errors::Strict => return Err(enc_err(enc, i, c)),
            Errors::Ignore => {}
            Errors::Replace => out.push(b'?'),
            Errors::BackslashReplace => {
                let esc = if cp > 0xffff {
                    format!("\\U{cp:08x}")
                } else if cp > 0xff {
                    format!("\\u{cp:04x}")
                } else {
                    format!("\\x{cp:02x}")
                };
                out.extend_from_slice(esc.as_bytes());
            }
            Errors::XmlCharRefReplace => out.extend_from_slice(format!("&#{cp};").as_bytes()),
            // A lone surrogate produced by `surrogateescape` decoding goes back
            // out as the byte it stood for.
            Errors::SurrogateEscape | Errors::SurrogatePass => {
                if (0xdc80..=0xdcff).contains(&cp) {
                    out.push((cp - 0xdc00) as u8);
                } else {
                    return Err(enc_err(enc, i, c));
                }
            }
        }
    }
    Ok(out)
}

/// Decode from a single-byte codec whose repertoire is `0..=limit`.
fn decode_single_byte(enc: &str, b: &[u8], limit: u32, errors: Errors) -> Result<String, String> {
    let mut out = String::with_capacity(b.len());
    for (i, &byte) in b.iter().enumerate() {
        if byte as u32 <= limit {
            out.push(byte as char);
            continue;
        }
        match errors {
            Errors::Strict => return Err(dec_err(enc, i, "ordinal not in range(128)")),
            Errors::Ignore => {}
            Errors::Replace => out.push('\u{fffd}'),
            Errors::SurrogateEscape => {
                // Undecodable bytes become U+DC80..U+DCFF, which is what makes
                // the mapping reversible.
                out.push(char::from_u32(0xdc00 + byte as u32).unwrap_or('\u{fffd}'));
            }
            _ => return Err(dec_err(enc, i, "ordinal not in range(128)")),
        }
    }
    Ok(out)
}

fn utf8_decode(b: &[u8], errors: Errors) -> Result<(String, usize), String> {
    match std::str::from_utf8(b) {
        Ok(s) => Ok((s.to_string(), b.len())),
        Err(e) => {
            let valid = e.valid_up_to();
            let mut out = String::from(std::str::from_utf8(&b[..valid]).unwrap_or(""));
            match errors {
                Errors::Strict => Err(dec_err("utf-8", valid, "invalid start byte")),
                _ => {
                    // Walk the remainder byte by byte, re-syncing on each valid
                    // sequence, applying the handler to everything that isn't.
                    let mut i = valid;
                    while i < b.len() {
                        match std::str::from_utf8(&b[i..]) {
                            Ok(rest) => {
                                out.push_str(rest);
                                i = b.len();
                            }
                            Err(e2) => {
                                let good = e2.valid_up_to();
                                if good > 0 {
                                    out.push_str(
                                        std::str::from_utf8(&b[i..i + good]).unwrap_or(""),
                                    );
                                    i += good;
                                    continue;
                                }
                                match errors {
                                    Errors::Ignore => {}
                                    Errors::Replace => out.push('\u{fffd}'),
                                    Errors::SurrogateEscape => out.push(
                                        char::from_u32(0xdc00 + b[i] as u32).unwrap_or('\u{fffd}'),
                                    ),
                                    _ => return Err(dec_err("utf-8", i, "invalid start byte")),
                                }
                                i += 1;
                            }
                        }
                    }
                    let n = out.chars().count();
                    Ok((out, n.max(b.len())))
                }
            }
        }
    }
}

/// utf-16/utf-32 in either byte order. `width` is 2 or 4.
fn utf_x_encode(s: &str, width: usize, big: bool, bom: bool) -> Vec<u8> {
    let mut out = Vec::with_capacity(s.len() * width + width);
    let push = |v: u32, out: &mut Vec<u8>| {
        let bytes: [u8; 4] = v.to_le_bytes();
        let take = &bytes[..width];
        if big {
            out.extend(take.iter().rev());
        } else {
            out.extend_from_slice(take);
        }
    };
    if bom {
        push(0xfeff, &mut out);
    }
    for c in s.chars() {
        let cp = c as u32;
        if width == 2 && cp > 0xffff {
            // Surrogate pair.
            let v = cp - 0x10000;
            push(0xd800 + (v >> 10), &mut out);
            push(0xdc00 + (v & 0x3ff), &mut out);
        } else {
            push(cp, &mut out);
        }
    }
    out
}

fn utf_x_decode(
    enc: &str,
    b: &[u8],
    width: usize,
    big: bool,
    errors: Errors,
) -> Result<String, String> {
    if b.len() % width != 0 && errors == Errors::Strict {
        return Err(dec_err(enc, b.len() - (b.len() % width), "truncated data"));
    }
    let mut units: Vec<u32> = Vec::with_capacity(b.len() / width);
    for chunk in b.chunks_exact(width) {
        let mut v: u32 = 0;
        if big {
            for &x in chunk {
                v = (v << 8) | x as u32;
            }
        } else {
            for (k, &x) in chunk.iter().enumerate() {
                v |= (x as u32) << (8 * k);
            }
        }
        units.push(v);
    }
    let mut out = String::new();
    let mut i = 0usize;
    while i < units.len() {
        let u = units[i];
        if width == 2 && (0xd800..0xdc00).contains(&u) {
            if let Some(&lo) = units.get(i + 1) {
                if (0xdc00..0xe000).contains(&lo) {
                    let cp = 0x10000 + ((u - 0xd800) << 10) + (lo - 0xdc00);
                    out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
                    i += 2;
                    continue;
                }
            }
        }
        match char::from_u32(u) {
            Some(c) => out.push(c),
            None => match errors {
                Errors::Strict => return Err(dec_err(enc, i * width, "illegal encoding")),
                Errors::Ignore => {}
                _ => out.push('\u{fffd}'),
            },
        }
        i += 1;
    }
    Ok(out)
}

fn as_text(h: &PyHost, v: &Value) -> Option<String> {
    h.as_str(v)
}

fn as_bytes(h: &PyHost, v: &Value) -> Option<Vec<u8>> {
    match h.get(v) {
        Some(PyObj::Bytes(b)) | Some(PyObj::Bytearray(b)) => Some(b.clone()),
        Some(PyObj::Str(s)) => Some(s.as_bytes().to_vec()),
        _ => match v {
            Value::Str(s) => Some(s.as_bytes().to_vec()),
            _ => None,
        },
    }
}

/// Normalize an encoding label the way CPython's registry does before search:
/// lowercase, and `-`/space to `_`.
fn normalize(name: &str) -> String {
    name.to_lowercase().replace([' ', '-'], "_")
}

/// The module's exported names. The per-codec functions the `encodings` package
/// reaches for are all here; anything else it needs it implements in Python.
pub fn entries(h: &mut PyHost) -> Vec<(String, Value)> {
    const NAMES: &[&str] = &[
        "register",
        "unregister",
        "lookup",
        "encode",
        "decode",
        "register_error",
        "lookup_error",
        "_forget_codec",
        "utf_8_encode",
        "utf_8_decode",
        "latin_1_encode",
        "latin_1_decode",
        "ascii_encode",
        "ascii_decode",
        "utf_16_encode",
        "utf_16_decode",
        "utf_16_le_encode",
        "utf_16_le_decode",
        "utf_16_be_encode",
        "utf_16_be_decode",
        "utf_32_encode",
        "utf_32_decode",
        "utf_32_le_encode",
        "utf_32_le_decode",
        "utf_32_be_encode",
        "utf_32_be_decode",
        "raw_unicode_escape_encode",
        "raw_unicode_escape_decode",
        "unicode_escape_encode",
        "unicode_escape_decode",
        "escape_encode",
        "escape_decode",
        "charmap_encode",
        "charmap_decode",
        "charmap_build",
        "readbuffer_encode",
    ];
    let mut out: Vec<(String, Value)> = Vec::new();
    for n in NAMES {
        let v = h.alloc(PyObj::Builtin(format!("_codecs.{n}")));
        out.push(((*n).to_string(), v));
    }
    out
}

/// Build the `(result, length)` tuple every codec function returns.
fn pair(h: &mut PyHost, v: Value, n: usize) -> Value {
    h.new_tuple(vec![v, Value::Int(n as i64)])
}

/// Entry points that must run OUTSIDE the host borrow: the registry calls back
/// into Python (a search function, a codec's own `encode`/`decode`), and doing
/// that while `with_host` holds the `RefCell` panics.
pub fn call_unborrowed(
    fname: &str,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Option<Result<Value, String>> {
    let kw = |n: &str| kwargs.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
    let hstr = |v: &Value| host::with_host(|h| h.as_str(v));
    Some(match fname {
        // ── registry ────────────────────────────────────────────────────────
        "register" => {
            if let Some(f) = args.first() {
                host::with_host(|h| h.codec_search.push(f.clone()));
            }
            Ok(Value::Undef)
        }
        "unregister" => {
            if let Some(f) = args.first() {
                let target = f.clone();
                host::with_host(|h| {
                    h.codec_search.retain(
                        |g| !matches!((g, &target), (Value::Obj(a), Value::Obj(b)) if a == b),
                    )
                });
            }
            Ok(Value::Undef)
        }
        "_forget_codec" => Ok(Value::Undef),
        "lookup" => (|| {
            let name = args
                .first()
                .and_then(hstr)
                .ok_or_else(|| host::type_error("lookup() argument must be str"))?;
            let norm = normalize(&name);
            if let Some(found) = host::with_host(|h| h.codec_cache.get(&norm).cloned()) {
                return Ok(found);
            }
            // CPython bootstraps the `encodings` package during interpreter
            // startup, which is what registers the search function that finds
            // every stdlib codec. Do it on first lookup instead.
            // Bootstrap at most once, and never re-entrantly: `encodings/__init__`
            // imports `codecs`, which looks a codec up, which would arrive back
            // here while `encodings` is still executing and recurse until the
            // stack died.
            if host::with_host(|h| h.codec_search.is_empty()) {
                thread_local! {
                    static BOOTSTRAPPING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
                }
                let first = BOOTSTRAPPING.with(|b| {
                    let was = b.get();
                    b.set(true);
                    !was
                });
                if first {
                    let _ = host::import_module("encodings");
                    BOOTSTRAPPING.with(|b| b.set(false));
                }
            }
            let searches = host::with_host(|h| h.codec_search.clone());
            for f in searches {
                let arg = host::with_host(|h| h.new_str(norm.clone()));
                let r = host::invoke(&f, vec![arg], vec![])?;
                if !matches!(r, Value::Undef) {
                    host::with_host(|h| h.codec_cache.insert(norm.clone(), r.clone()));
                    return Ok(r);
                }
            }
            Err(format!("LookupError: unknown encoding: {name}"))
        })(),
        "register_error" => {
            if let (Some(n), Some(f)) = (args.first().and_then(hstr), args.get(1)) {
                let fv = f.clone();
                host::with_host(|h| h.codec_errors.insert(n, fv));
            }
            Ok(Value::Undef)
        }
        "lookup_error" => (|| {
            let n = args
                .first()
                .and_then(hstr)
                .ok_or_else(|| host::type_error("lookup_error() argument must be str"))?;
            match host::with_host(|h| h.codec_errors.get(&n).cloned()) {
                Some(f) => Ok(f),
                // The built-in handlers are implemented inside the codecs, not as
                // callables; hand back a marker so `codecs.lookup_error('strict')`
                // resolves rather than raising.
                None if matches!(
                    n.as_str(),
                    "strict"
                        | "ignore"
                        | "replace"
                        | "backslashreplace"
                        | "xmlcharrefreplace"
                        | "surrogateescape"
                        | "surrogatepass"
                        | "namereplace"
                ) =>
                {
                    Ok(host::with_host(|h| {
                        h.alloc(PyObj::Builtin(format!("_codecs.{n}_errors")))
                    }))
                }
                None => Err(format!("LookupError: unknown error handler name '{n}'")),
            }
        })(),

        // ── generic entry points ────────────────────────────────────────────
        // `encode(obj, encoding='utf-8', errors='strict')` — resolve through the
        // registry and call the codec's encoder.
        "encode" | "decode" => (|| {
            let obj = args.first().cloned().ok_or_else(|| {
                host::type_error(&format!("{fname}() missing required argument 'obj'"))
            })?;
            let enc = args
                .get(1)
                .cloned()
                .or_else(|| kw("encoding"))
                .and_then(|v| hstr(&v))
                .unwrap_or_else(|| "utf-8".to_string());
            let err_name = args
                .get(2)
                .cloned()
                .or_else(|| kw("errors"))
                .and_then(|v| hstr(&v))
                .unwrap_or_else(|| "strict".to_string());
            // Try the native codecs first; fall back to the registry (which is
            // how the pure-Python `encodings` modules get used).
            let direct = format!("{}_{fname}", normalize(&enc));
            let native = [
                "utf_8_encode",
                "utf_8_decode",
                "latin_1_encode",
                "latin_1_decode",
                "ascii_encode",
                "ascii_decode",
                "utf_16_encode",
                "utf_16_decode",
                "utf_16_le_encode",
                "utf_16_le_decode",
                "utf_16_be_encode",
                "utf_16_be_decode",
                "utf_32_encode",
                "utf_32_decode",
            ];
            let alias = match normalize(&enc).as_str() {
                "utf8" | "u8" | "utf" => "utf_8".to_string(),
                "latin1" | "latin" | "l1" | "iso8859_1" | "iso_8859_1" | "8859" | "cp819" => {
                    "latin_1".to_string()
                }
                "us_ascii" | "646" => "ascii".to_string(),
                "utf16" => "utf_16".to_string(),
                "utf32" => "utf_32".to_string(),
                other => other.to_string(),
            };
            let direct2 = format!("{alias}_{fname}");
            for cand in [direct.as_str(), direct2.as_str()] {
                if native.contains(&cand) {
                    let e = host::with_host(|h| h.new_str(err_name.clone()));
                    let cand_owned = cand.to_string();
                    let a = vec![obj.clone(), e];
                    let r = host::with_host(|h| call(h, &cand_owned, &a, &[]))
                        .expect("native codec name")?;
                    // The per-codec functions return `(value, length)`; the
                    // generic ones return just the value.
                    return Ok(host::with_host(|h| match h.get(&r) {
                        Some(PyObj::Tuple(t)) if !t.is_empty() => t[0].clone(),
                        _ => r.clone(),
                    }));
                }
            }
            // Registry path: `lookup(enc)` then `.encode`/`.decode`.
            let name_v = host::with_host(|h| h.new_str(enc.clone()));
            let info = call_unborrowed("lookup", &[name_v], &[]).expect("lookup")?;
            let f = host::with_host(|h| h.get_attr(&info, fname))?;
            let e = host::with_host(|h| h.new_str(err_name));
            let r = host::invoke(&f, vec![obj, e], vec![])?;
            Ok(host::with_host(|h| match h.get(&r) {
                Some(PyObj::Tuple(t)) if !t.is_empty() => t[0].clone(),
                _ => r.clone(),
            }))
        })(),

        _ => return None,
    })
}

/// Dispatch `_codecs.<fname>`.
pub fn call(
    h: &mut PyHost,
    fname: &str,
    args: &[Value],
    kwargs: &[(String, Value)],
) -> Option<Result<Value, String>> {
    let kw = |n: &str| kwargs.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
    let errors_of = |h: &PyHost, idx: usize| -> Errors {
        args.get(idx)
            .cloned()
            .or_else(|| kw("errors"))
            .and_then(|v| h.as_str(&v))
            .map(|s| Errors::parse(&s))
            .unwrap_or(Errors::Strict)
    };
    Some(match fname {
        // ── native codecs ───────────────────────────────────────────────────
        "utf_8_encode" => (|| {
            let s = as_text(
                h,
                args.first()
                    .ok_or_else(|| host::type_error("utf_8_encode"))?,
            )
            .ok_or_else(|| host::type_error("utf_8_encode() argument 1 must be str"))?;
            let n = s.chars().count();
            // Fast path, as in RustPython: a str is already utf-8.
            let b = h.alloc(PyObj::Bytes(s.into_bytes()));
            Ok(pair(h, b, n))
        })(),
        "utf_8_decode" => (|| {
            let b = as_bytes(
                h,
                args.first()
                    .ok_or_else(|| host::type_error("utf_8_decode"))?,
            )
            .ok_or_else(|| host::type_error("utf_8_decode() argument 1 must be bytes"))?;
            let (s, n) = utf8_decode(&b, errors_of(h, 1))?;
            let sv = h.new_str(s);
            Ok(pair(h, sv, n))
        })(),
        "latin_1_encode" | "ascii_encode" => (|| {
            let limit = if fname.starts_with("ascii") {
                0x7f
            } else {
                0xff
            };
            let name = if limit == 0x7f { "ascii" } else { "latin-1" };
            let s = as_text(h, args.first().ok_or_else(|| host::type_error(fname))?)
                .ok_or_else(|| host::type_error("argument 1 must be str"))?;
            let n = s.chars().count();
            let out = encode_single_byte(name, &s, limit, errors_of(h, 1))?;
            let b = h.alloc(PyObj::Bytes(out));
            Ok(pair(h, b, n))
        })(),
        "latin_1_decode" | "ascii_decode" => (|| {
            let limit = if fname.starts_with("ascii") {
                0x7f
            } else {
                0xff
            };
            let name = if limit == 0x7f { "ascii" } else { "latin-1" };
            let b = as_bytes(h, args.first().ok_or_else(|| host::type_error(fname))?)
                .ok_or_else(|| host::type_error("argument 1 must be bytes"))?;
            let s = decode_single_byte(name, &b, limit, errors_of(h, 1))?;
            let n = b.len();
            let sv = h.new_str(s);
            Ok(pair(h, sv, n))
        })(),
        // `readbuffer_encode(obj)` — the identity byte view.
        "readbuffer_encode" => (|| {
            let b = as_bytes(h, args.first().ok_or_else(|| host::type_error(fname))?)
                .ok_or_else(|| host::type_error("argument 1 must be bytes-like"))?;
            let n = b.len();
            let v = h.alloc(PyObj::Bytes(b));
            Ok(pair(h, v, n))
        })(),
        _ if fname.starts_with("utf_16") || fname.starts_with("utf_32") => (|| {
            let width = if fname.starts_with("utf_16") { 2 } else { 4 };
            let big = fname.contains("_be_");
            let native_le = !fname.contains("_be_") && !fname.contains("_le_");
            if fname.ends_with("_encode") {
                let s = as_text(h, args.first().ok_or_else(|| host::type_error(fname))?)
                    .ok_or_else(|| host::type_error("argument 1 must be str"))?;
                let n = s.chars().count();
                // The BOM-less forms are the explicit `_le_`/`_be_` ones; the
                // plain name emits a BOM, as CPython does.
                let out = utf_x_encode(&s, width, big, native_le);
                let b = h.alloc(PyObj::Bytes(out));
                Ok(pair(h, b, n))
            } else {
                let mut b = as_bytes(h, args.first().ok_or_else(|| host::type_error(fname))?)
                    .ok_or_else(|| host::type_error("argument 1 must be bytes"))?;
                let mut big = big;
                if native_le && b.len() >= width {
                    // Consume a BOM and let it pick the byte order.
                    let head: Vec<u8> = b[..width].to_vec();
                    let le_bom: Vec<u8> = if width == 2 {
                        vec![0xff, 0xfe]
                    } else {
                        vec![0xff, 0xfe, 0, 0]
                    };
                    let be_bom: Vec<u8> = if width == 2 {
                        vec![0xfe, 0xff]
                    } else {
                        vec![0, 0, 0xfe, 0xff]
                    };
                    if head == le_bom {
                        big = false;
                        b.drain(..width);
                    } else if head == be_bom {
                        big = true;
                        b.drain(..width);
                    }
                }
                let name = if width == 2 { "utf-16" } else { "utf-32" };
                let s = utf_x_decode(name, &b, width, big, errors_of(h, 1))?;
                let n = b.len();
                let sv = h.new_str(s);
                Ok(pair(h, sv, n))
            }
        })(),
        // The escape and charmap codecs stay in Python (`encodings`), matching
        // RustPython's split; these entry points exist so a `from _codecs import
        // *` finds the names.
        _ => Err(format!(
            "NotImplementedError: _codecs.{fname} is provided by the encodings package"
        )),
    })
}