Skip to content

builtins: Implement ascii builtin API #1181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 28, 2019
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