| 44 | #[pyfunction(name = "b2a_hex")] |
| 45 | #[pyfunction] |
| 46 | fn hexlify( |
| 47 | data: ArgBytesLike, |
| 48 | sep: OptionalArg<ArgAsciiBuffer>, |
| 49 | bytes_per_sep: OptionalArg<isize>, |
| 50 | vm: &VirtualMachine, |
| 51 | ) -> PyResult<Vec<u8>> { |
| 52 | let bytes_per_sep = bytes_per_sep.unwrap_or(1); |
| 53 | |
| 54 | data.with_ref(|bytes| { |
| 55 | // Get separator character if provided |
| 56 | let sep_char = if let OptionalArg::Present(sep_buf) = sep { |
| 57 | sep_buf.with_ref(|sep_bytes| { |
| 58 | if sep_bytes.len() != 1 { |
| 59 | return Err(vm.new_value_error("sep must be length 1.")); |
| 60 | } |
| 61 | let sep_char = sep_bytes[0]; |
| 62 | if !sep_char.is_ascii() { |
| 63 | return Err(vm.new_value_error("sep must be ASCII.")); |
| 64 | } |
| 65 | Ok(Some(sep_char)) |
| 66 | })? |
| 67 | } else { |
| 68 | None |
| 69 | }; |
| 70 | |
| 71 | // If no separator or bytes_per_sep is 0, use simple hexlify |
| 72 | if sep_char.is_none() || bytes_per_sep == 0 || bytes.is_empty() { |
| 73 | let mut hex = Vec::<u8>::with_capacity(bytes.len() * 2); |
| 74 | for b in bytes { |
| 75 | hex.push(hex_nibble(b >> 4)); |
| 76 | hex.push(hex_nibble(b & 0xf)); |
| 77 | } |
| 78 | return Ok(hex); |
| 79 | } |
| 80 | |
| 81 | let sep_char = sep_char.unwrap(); |
| 82 | let abs_bytes_per_sep = bytes_per_sep.unsigned_abs(); |
| 83 | |
| 84 | // If separator interval is >= data length, no separators needed |
| 85 | if abs_bytes_per_sep >= bytes.len() { |
| 86 | let mut hex = Vec::<u8>::with_capacity(bytes.len() * 2); |
| 87 | for b in bytes { |
| 88 | hex.push(hex_nibble(b >> 4)); |
| 89 | hex.push(hex_nibble(b & 0xf)); |
| 90 | } |
| 91 | return Ok(hex); |
| 92 | } |
| 93 | |
| 94 | // Calculate result length |
| 95 | let num_separators = (bytes.len() - 1) / abs_bytes_per_sep; |
| 96 | let result_len = bytes.len() * 2 + num_separators; |
| 97 | let mut hex = vec![0u8; result_len]; |
| 98 | |
| 99 | if bytes_per_sep < 0 { |
| 100 | // Left-to-right processing (negative bytes_per_sep) |
| 101 | let mut i = 0; // input index |
| 102 | let mut j = 0; // output index |
| 103 | let chunks = bytes.len() / abs_bytes_per_sep; |