Skip to content

Commit 0584b85

Browse files
committed
Bytearray hex formatting
1 parent a264017 commit 0584b85

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

vm/src/obj/objbytearray.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::cell::RefCell;
44
use std::ops::{Deref, DerefMut};
5+
use std::fmt::Write;
56

67
use crate::pyobject::{
78
PyContext, PyFuncArgs, PyObject, PyObjectPayload, PyObjectPayload2, PyObjectRef, PyResult,
@@ -311,10 +312,19 @@ fn set_value(obj: &PyObjectRef, value: Vec<u8>) {
311312
}
312313
*/
313314

315+
/// Return a lowercase hex representation of a bytearray
316+
fn bytearray_to_hex(bytearray: &[u8]) -> String {
317+
bytearray.iter().fold(String::new(), |mut s, b| {
318+
let _ = write!(s, "\\x{:02x}", b);
319+
s
320+
})
321+
}
322+
314323
fn bytearray_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
315324
arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]);
316325
let value = get_value(obj);
317-
let data = String::from_utf8(value.to_vec()).unwrap();
326+
let data =
327+
String::from_utf8(value.to_vec()).unwrap_or_else(|_| bytearray_to_hex(&value.to_vec()));
318328
Ok(vm.new_str(format!("bytearray(b'{}')", data)))
319329
}
320330

@@ -346,3 +356,13 @@ fn bytearray_upper(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
346356
let value = get_value(obj).to_vec().to_ascii_uppercase();
347357
Ok(vm.ctx.new_bytearray(value))
348358
}
359+
360+
#[cfg(test)]
361+
mod tests {
362+
use super::*;
363+
364+
#[test]
365+
fn bytearray_to_hex_formatting() {
366+
assert_eq!(&bytearray_to_hex(&[11u8, 222u8]), "\\x0b\\xde");
367+
}
368+
}

0 commit comments

Comments
 (0)