|
2 | 2 |
|
3 | 3 | use std::cell::RefCell;
|
4 | 4 | use std::ops::{Deref, DerefMut};
|
| 5 | +use std::fmt::Write; |
5 | 6 |
|
6 | 7 | use crate::pyobject::{
|
7 | 8 | PyContext, PyFuncArgs, PyObject, PyObjectPayload, PyObjectPayload2, PyObjectRef, PyResult,
|
@@ -311,10 +312,19 @@ fn set_value(obj: &PyObjectRef, value: Vec<u8>) {
|
311 | 312 | }
|
312 | 313 | */
|
313 | 314 |
|
| 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 | + |
314 | 323 | fn bytearray_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
315 | 324 | arg_check!(vm, args, required = [(obj, Some(vm.ctx.bytearray_type()))]);
|
316 | 325 | 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())); |
318 | 328 | Ok(vm.new_str(format!("bytearray(b'{}')", data)))
|
319 | 329 | }
|
320 | 330 |
|
@@ -346,3 +356,13 @@ fn bytearray_upper(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
346 | 356 | let value = get_value(obj).to_vec().to_ascii_uppercase();
|
347 | 357 | Ok(vm.ctx.new_bytearray(value))
|
348 | 358 | }
|
| 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