mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-09 22:49:57 +09:00
builtins: Implement ascii builtin API
This commit is contained in:
4
tests/snippets/builtin_ascii.py
Normal file
4
tests/snippets/builtin_ascii.py
Normal 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'
|
||||
@@ -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(),
|
||||
|
||||
Reference in New Issue
Block a user