Merge pull request #1181 from corona10/builtin_ascii

builtins: Implement ascii builtin API
This commit is contained in:
Windel Bouwman
2019-07-28 10:00:50 +02:00
committed by GitHub
2 changed files with 18 additions and 1 deletions

View File

@@ -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'

View File

@@ -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();
@@ -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(),