Skip to content

Commit 8dd664e

Browse files
committed
Add binascii.hexlify
1 parent f7531d8 commit 8dd664e

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

tests/snippets/stdlib_binascii.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,14 @@
11
import binascii
2+
from testutils import assertRaises
3+
4+
5+
# hexlify tests
6+
h = binascii.hexlify
7+
8+
assert h(b"abc") == b"616263"
9+
assert h(1000 * b"x") == 1000 * b"78"
10+
# bytearray not supported yet
11+
# assert h(bytearray(b"a")) = b"61"
12+
13+
with assertRaises(TypeError):
14+
h("a")

vm/src/stdlib/binascii.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,33 @@
1-
use crate::pyobject::PyObjectRef;
1+
use crate::function::PyFuncArgs;
2+
use crate::obj::objbytes;
3+
use crate::pyobject::{PyObjectRef, PyResult};
24
use crate::vm::VirtualMachine;
35

6+
fn hex_nibble(n: u8) -> u8 {
7+
match n {
8+
0..=9 => b'0' + n,
9+
10..=15 => b'a' + n,
10+
_ => unreachable!(),
11+
}
12+
}
13+
14+
fn binascii_hexlify(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
15+
arg_check!(vm, args, required = [(data, Some(vm.ctx.bytes_type()))]);
16+
17+
let bytes = objbytes::get_value(data);
18+
let mut hex = Vec::<u8>::with_capacity(bytes.len() * 2);
19+
for b in bytes.iter() {
20+
hex.push(hex_nibble(b >> 4));
21+
hex.push(hex_nibble(b & 0xf));
22+
}
23+
24+
Ok(vm.ctx.new_bytes(hex))
25+
}
26+
427
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
28+
let ctx = &vm.ctx;
29+
530
py_module!(vm, "binascii", {
31+
"hexlify" => ctx.new_rustfunc(binascii_hexlify),
632
})
733
}

0 commit comments

Comments
 (0)