MCPcopy Index your code
hub / github.com/RustPython/RustPython / maketrans

Method maketrans

crates/vm/src/builtins/str.rs:1399–1472  ·  view source on GitHub ↗
(
        dict_or_str: PyObjectRef,
        to_str: OptionalArg<PyStrRef>,
        none_str: OptionalArg<PyStrRef>,
        vm: &VirtualMachine,
    )

Source from the content-addressed store, hash-verified

1397
1398 #[pystaticmethod]
1399 fn maketrans(
1400 dict_or_str: PyObjectRef,
1401 to_str: OptionalArg<PyStrRef>,
1402 none_str: OptionalArg<PyStrRef>,
1403 vm: &VirtualMachine,
1404 ) -> PyResult {
1405 let new_dict = vm.ctx.new_dict();
1406 if let OptionalArg::Present(to_str) = to_str {
1407 match dict_or_str.downcast::<Self>() {
1408 Ok(from_str) => {
1409 if to_str.len() == from_str.len() {
1410 for (c1, c2) in from_str
1411 .as_wtf8()
1412 .code_points()
1413 .zip(to_str.as_wtf8().code_points())
1414 {
1415 new_dict.set_item(
1416 &*vm.new_pyobj(c1.to_u32()),
1417 vm.new_pyobj(c2.to_u32()),
1418 vm,
1419 )?;
1420 }
1421 if let OptionalArg::Present(none_str) = none_str {
1422 for c in none_str.as_wtf8().code_points() {
1423 new_dict.set_item(&*vm.new_pyobj(c.to_u32()), vm.ctx.none(), vm)?;
1424 }
1425 }
1426 Ok(new_dict.to_pyobject(vm))
1427 } else {
1428 Err(vm.new_value_error(
1429 "the first two maketrans arguments must have equal length",
1430 ))
1431 }
1432 }
1433 _ => Err(vm.new_type_error(
1434 "first maketrans argument must be a string if there is a second argument",
1435 )),
1436 }
1437 } else {
1438 // dict_str must be a dict
1439 match dict_or_str.downcast::<PyDict>() {
1440 Ok(dict) => {
1441 for (key, val) in dict {
1442 // FIXME: ints are key-compatible
1443 if let Some(num) = key.downcast_ref::<PyInt>() {
1444 new_dict.set_item(
1445 &*num.as_bigint().to_i32().to_pyobject(vm),
1446 val,
1447 vm,
1448 )?;
1449 } else if let Some(string) = key.downcast_ref::<Self>() {
1450 if string.len() == 1 {
1451 let num_value =
1452 string.as_wtf8().code_points().next().unwrap().to_u32();
1453 new_dict.set_item(&*num_value.to_pyobject(vm), val, vm)?;
1454 } else {
1455 return Err(vm.new_value_error(
1456 "string keys in translate table must be of length 1",

Callers

nothing calls this directly

Calls 13

new_dictMethod · 0.80
code_pointsMethod · 0.80
new_pyobjMethod · 0.80
noneMethod · 0.80
as_bigintMethod · 0.80
ErrClass · 0.50
lenMethod · 0.45
as_wtf8Method · 0.45
set_itemMethod · 0.45
to_u32Method · 0.45
to_pyobjectMethod · 0.45
unwrapMethod · 0.45

Tested by

no test coverage detected