Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions tests/snippets/builtin_ascii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
assert ascii('hello world') == "'hello world'"
assert ascii('안녕 세상') == "'\\uc548\\ub155 \\uc138\\uc0c1'"
assert ascii('안녕 RustPython') == "'\\uc548\\ub155 RustPython'"
assert ascii(5) == '5'
15 changes: 14 additions & 1 deletion vm/src/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,19 @@ fn builtin_any(iterable: PyIterable<bool>, vm: &VirtualMachine) -> PyResult<bool
Ok(false)
}

// builtin_ascii
fn builtin_ascii(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
let repr = vm.to_repr(&obj)?;
let mut ascii = String::new();
for c in repr.value.chars() {
if c.is_ascii() {
ascii.push(c)
} else {
let hex = format!("\\u{:x}", c as i64);
ascii.push_str(&hex)
}
}
Ok(ascii)
}

fn builtin_bin(x: PyIntRef, _vm: &VirtualMachine) -> String {
let x = x.as_bigint();
Expand Down Expand Up @@ -788,6 +800,7 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef) {
"abs" => ctx.new_rustfunc(builtin_abs),
"all" => ctx.new_rustfunc(builtin_all),
"any" => ctx.new_rustfunc(builtin_any),
"ascii" => ctx.new_rustfunc(builtin_ascii),
"bin" => ctx.new_rustfunc(builtin_bin),
"bool" => ctx.bool_type(),
"bytearray" => ctx.bytearray_type(),
Expand Down