MCPcopy Index your code
hub / github.com/RustPython/RustPython / to_bytes

Method to_bytes

crates/vm/src/builtins/int.rs:553–596  ·  view source on GitHub ↗
(&self, args: IntToByteArgs, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

551
552 #[pymethod]
553 fn to_bytes(&self, args: IntToByteArgs, vm: &VirtualMachine) -> PyResult<PyBytes> {
554 let signed = args.signed.map_or(false, Into::into);
555 let byte_len = args.length;
556
557 let value = self.as_bigint();
558 match value.sign() {
559 Sign::Minus if !signed => {
560 return Err(vm.new_overflow_error("can't convert negative int to unsigned"));
561 }
562 Sign::NoSign => return Ok(vec![0u8; byte_len].into()),
563 _ => {}
564 }
565
566 let mut origin_bytes = match (args.byteorder, signed) {
567 (ArgByteOrder::Big, true) => value.to_signed_bytes_be(),
568 (ArgByteOrder::Big, false) => value.to_bytes_be().1,
569 (ArgByteOrder::Little, true) => value.to_signed_bytes_le(),
570 (ArgByteOrder::Little, false) => value.to_bytes_le().1,
571 };
572
573 let origin_len = origin_bytes.len();
574 if origin_len > byte_len {
575 return Err(vm.new_overflow_error("int too big to convert"));
576 }
577
578 let mut append_bytes = match value.sign() {
579 Sign::Minus => vec![255u8; byte_len - origin_len],
580 _ => vec![0u8; byte_len - origin_len],
581 };
582
583 let bytes = match args.byteorder {
584 ArgByteOrder::Big => {
585 let mut bytes = append_bytes;
586 bytes.append(&mut origin_bytes);
587 bytes
588 }
589 ArgByteOrder::Little => {
590 let mut bytes = origin_bytes;
591 bytes.append(&mut append_bytes);
592 bytes
593 }
594 };
595 Ok(bytes.into())
596 }
597
598 #[pygetset]
599 fn real(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {

Callers 15

_write_objectMethod · 0.80
v4_int_to_packedFunction · 0.80
v6_int_to_packedFunction · 0.80
_prefix_from_ip_intMethod · 0.80
_string_from_ip_intMethod · 0.80
_b32decodeFunction · 0.80
randbytesMethod · 0.80
encode_longFunction · 0.80
_get_code_arrayFunction · 0.80
bytesMethod · 0.80
innerFunction · 0.80
runMethod · 0.80

Calls 4

as_bigintMethod · 0.80
ErrClass · 0.50
lenMethod · 0.45
appendMethod · 0.45

Tested by 15

runMethod · 0.64
buildMethod · 0.64
test_deep_nestingMethod · 0.64
checkMethod · 0.64
test_to_bytesMethod · 0.64
test_from_bytes_smallMethod · 0.64
test_new_typeMethod · 0.64
setUpModuleFunction · 0.64
test_invalid_dictMethod · 0.64
test_uuid7Method · 0.64