Skip to content

Commit 57ef8b3

Browse files
Merge pull request RustPython#1181 from corona10/builtin_ascii
builtins: Implement ascii builtin API
2 parents c786109 + aecb151 commit 57ef8b3

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

tests/snippets/builtin_ascii.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
assert ascii('hello world') == "'hello world'"
2+
assert ascii('안녕 세상') == "'\\uc548\\ub155 \\uc138\\uc0c1'"
3+
assert ascii('안녕 RustPython') == "'\\uc548\\ub155 RustPython'"
4+
assert ascii(5) == '5'

vm/src/builtins.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,19 @@ fn builtin_any(iterable: PyIterable<bool>, vm: &VirtualMachine) -> PyResult<bool
5959
Ok(false)
6060
}
6161

62-
// builtin_ascii
62+
fn builtin_ascii(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
63+
let repr = vm.to_repr(&obj)?;
64+
let mut ascii = String::new();
65+
for c in repr.value.chars() {
66+
if c.is_ascii() {
67+
ascii.push(c)
68+
} else {
69+
let hex = format!("\\u{:x}", c as i64);
70+
ascii.push_str(&hex)
71+
}
72+
}
73+
Ok(ascii)
74+
}
6375

6476
fn builtin_bin(x: PyIntRef, _vm: &VirtualMachine) -> String {
6577
let x = x.as_bigint();
@@ -788,6 +800,7 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef) {
788800
"abs" => ctx.new_rustfunc(builtin_abs),
789801
"all" => ctx.new_rustfunc(builtin_all),
790802
"any" => ctx.new_rustfunc(builtin_any),
803+
"ascii" => ctx.new_rustfunc(builtin_ascii),
791804
"bin" => ctx.new_rustfunc(builtin_bin),
792805
"bool" => ctx.bool_type(),
793806
"bytearray" => ctx.bytearray_type(),

0 commit comments

Comments
 (0)