Skip to content

Commit 0bdba72

Browse files
authored
Accept bytes in Unicode name lookup (#9585)
Match CPython Unicode name conversion for bytes and surrogate-containing strings, including the byte-length limit and failed-name formatting. Assisted-by: OpenAI Codex:model version not exposed
1 parent 7e1c3e9 commit 0bdba72

1 file changed

Lines changed: 19 additions & 4 deletions

File tree

‎crates/stdlib/src/unicodedata.rs‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ mod unicodedata {
3434
use super::{NormalizeFormArg, unicode_core};
3535
use crate::vm::{
3636
Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
37-
builtins::{PyModule, PyStr, PyStrRef},
37+
builtins::{PyBytes, PyModule, PyStr, PyStrRef, PyUtf8Str},
3838
common::lock::PyMutex,
3939
function::OptionalArg,
4040
protocol::PyIterReturn,
@@ -351,18 +351,33 @@ mod unicodedata {
351351
}
352352

353353
#[pymethod]
354-
fn lookup(zelf: &Py<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
355-
if let Some(name_str) = name.to_str()
354+
fn lookup(zelf: &Py<Self>, name: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
355+
let name_bytes = if let Some(bytes) = name.downcast_ref::<PyBytes>() {
356+
bytes.as_bytes()
357+
} else {
358+
name.try_downcast_ref::<PyUtf8Str>(vm)?.as_bytes()
359+
};
360+
// CPython's generated Unicode name database limits names to 256 bytes.
361+
if name_bytes.len() > 256 {
362+
return Err(vm.new_key_error(vm.ctx.new_str("name too long").into()));
363+
}
364+
if let Ok(name_str) = core::str::from_utf8(name_bytes)
356365
&& let Some(found) = zelf.inner.lookup(name_str)
357366
{
358367
return Ok(match found {
359368
unicode_core::LookupResult::Character(ch) => ch.to_string(),
360369
unicode_core::LookupResult::Sequence(seq) => seq.to_string(),
361370
});
362371
}
372+
// CPython formats the failed name as a NUL-terminated UTF-8 string.
373+
let prefix = name_bytes
374+
.split(|&byte| byte == 0)
375+
.next()
376+
.unwrap_or_default();
377+
let display = String::from_utf8_lossy(prefix);
363378
Err(vm.new_key_error(
364379
vm.ctx
365-
.new_str(format!("undefined character name '{name}'"))
380+
.new_str(format!("undefined character name '{display}'"))
366381
.into(),
367382
))
368383
}

0 commit comments

Comments
 (0)