Skip to content

Add bytes.maketrans #873

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

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 8 additions & 0 deletions tests/snippets/bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,11 @@
with assertRaises(TypeError):
b"b".center(2, b"ba")
b"kok".center(5, bytearray(b"x"))

assert bytes.maketrans(b'', b'') == bytes(range(0, 256))
trans1, trans2 = b'dcba0123', b'8900xyzz'
manual_map = list(range(0, 256))
for c1, c2 in zip(trans1, trans2):
manual_map[c1] = c2

assert bytes(manual_map) == bytes.maketrans(trans1, trans2)
20 changes: 19 additions & 1 deletion vm/src/obj/objbytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyVa
use super::objbyteinner::{is_byte, PyByteInner};
use super::objiter;
use super::objslice::PySlice;
use super::objtype::PyClassRef;
use super::objtype::{self, PyClassRef};

/// "bytes(iterable_of_ints) -> bytes\n\
/// bytes(string, encoding[, errors]) -> bytes\n\
Expand Down Expand Up @@ -63,6 +63,7 @@ pub fn init(context: &PyContext) {
let bytes_type = &context.bytes_type;
extend_class!(context, bytes_type, {
"fromhex" => context.new_rustfunc(PyBytesRef::fromhex),
"maketrans" => context.new_rustfunc(PyBytesRef::maketrans),
});
let bytesiterator_type = &context.bytesiterator_type;
extend_class!(context, bytesiterator_type, {
Expand Down Expand Up @@ -234,6 +235,23 @@ impl PyBytesRef {
)
}

fn maketrans(frm: PyObjectRef, to: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if !objtype::isinstance(&frm, &vm.ctx.bytes_type())
|| !objtype::isinstance(&to, &vm.ctx.bytes_type())
{
return Err(vm.new_type_error(format!("TypeError: a bytes-like object is required")));
}
let frm = get_value(&frm);
let to = get_value(&to);

let mut table: Vec<u8> = (0..=255).collect();
for (i, c) in frm.iter().enumerate() {
table[*c as usize] = to[i];
}

Ok(vm.ctx.new_bytes(table))
}

#[pymethod(name = "center")]
fn center(
self,
Expand Down