(
vm: &VirtualMachine,
format_string: &[u8],
values_obj: PyObjectRef,
)
| 282 | } |
| 283 | |
| 284 | pub(crate) fn cformat_bytes( |
| 285 | vm: &VirtualMachine, |
| 286 | format_string: &[u8], |
| 287 | values_obj: PyObjectRef, |
| 288 | ) -> PyResult<Vec<u8>> { |
| 289 | let mut format = CFormatBytes::parse_from_bytes(format_string) |
| 290 | .map_err(|err| vm.new_value_error(err.to_string()))?; |
| 291 | let (num_specifiers, mapping_required) = format |
| 292 | .check_specifiers() |
| 293 | .ok_or_else(|| specifier_error(vm))?; |
| 294 | |
| 295 | let mut result = vec![]; |
| 296 | |
| 297 | let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__)) |
| 298 | && !values_obj.fast_isinstance(vm.ctx.types.tuple_type) |
| 299 | && !values_obj.fast_isinstance(vm.ctx.types.bytes_type) |
| 300 | && !values_obj.fast_isinstance(vm.ctx.types.bytearray_type); |
| 301 | |
| 302 | if num_specifiers == 0 { |
| 303 | // literal only |
| 304 | return if is_mapping |
| 305 | || values_obj |
| 306 | .downcast_ref::<tuple::PyTuple>() |
| 307 | .is_some_and(|e| e.is_empty()) |
| 308 | { |
| 309 | for (_, part) in format.iter_mut() { |
| 310 | match part { |
| 311 | CFormatPart::Literal(literal) => result.append(literal), |
| 312 | CFormatPart::Spec(_) => unreachable!(), |
| 313 | } |
| 314 | } |
| 315 | Ok(result) |
| 316 | } else { |
| 317 | Err(vm.new_type_error("not all arguments converted during bytes formatting")) |
| 318 | }; |
| 319 | } |
| 320 | |
| 321 | if mapping_required { |
| 322 | // dict |
| 323 | return if is_mapping { |
| 324 | for (_, part) in format { |
| 325 | match part { |
| 326 | CFormatPart::Literal(literal) => result.extend(literal), |
| 327 | CFormatPart::Spec(CFormatSpecKeyed { mapping_key, spec }) => { |
| 328 | let key = mapping_key.unwrap(); |
| 329 | let value = values_obj.get_item(&key, vm)?; |
| 330 | let part_result = spec_format_bytes(vm, &spec, value)?; |
| 331 | result.extend(part_result); |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | Ok(result) |
| 336 | } else { |
| 337 | Err(vm.new_type_error("format requires a mapping")) |
| 338 | }; |
| 339 | } |
| 340 | |
| 341 | // tuple |
no test coverage detected