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

Method try_int

crates/vm/src/protocol/number.rs:47–90  ·  view source on GitHub ↗
(&self, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

45 }
46
47 pub fn try_int(&self, vm: &VirtualMachine) -> PyResult<PyIntRef> {
48 fn try_convert(obj: &PyObject, lit: &[u8], vm: &VirtualMachine) -> PyResult<PyIntRef> {
49 let base = 10;
50 let digit_limit = vm.state.int_max_str_digits.load();
51
52 let i = bytes_to_int(lit, base, digit_limit)
53 .map_err(|e| handle_bytes_to_int_err(e, obj, vm))?;
54 Ok(PyInt::from(i).into_ref(&vm.ctx))
55 }
56
57 if let Some(i) = self.downcast_ref_if_exact::<PyInt>(vm) {
58 Ok(i.to_owned())
59 } else if let Some(i) = self.number().int(vm).or_else(|| self.try_index_opt(vm)) {
60 i
61 } else if let Ok(Some(f)) = vm.get_special_method(self, identifier!(vm, __trunc__)) {
62 _warnings::warn(
63 vm.ctx.exceptions.deprecation_warning,
64 "The delegation of int() to __trunc__ is deprecated.".to_owned(),
65 1,
66 vm,
67 )?;
68 let ret = f.invoke((), vm)?;
69 ret.try_index(vm).map_err(|_| {
70 vm.new_type_error(format!(
71 "__trunc__ returned non-Integral (type {})",
72 ret.class()
73 ))
74 })
75 } else if let Some(s) = self.downcast_ref::<PyStr>() {
76 try_convert(self, s.as_wtf8().trim().as_bytes(), vm)
77 } else if let Some(bytes) = self.downcast_ref::<PyBytes>() {
78 try_convert(self, bytes, vm)
79 } else if let Some(bytearray) = self.downcast_ref::<PyByteArray>() {
80 try_convert(self, &bytearray.borrow_buf(), vm)
81 } else if let Ok(buffer) = ArgBytesLike::try_from_borrowed_object(vm, self) {
82 // TODO: replace to PyBuffer
83 try_convert(self, &buffer.borrow_buf(), vm)
84 } else {
85 Err(vm.new_type_error(format!(
86 "int() argument must be a string, a bytes-like object or a real number, not '{}'",
87 self.class()
88 )))
89 }
90 }
91
92 pub fn try_float_opt(&self, vm: &VirtualMachine) -> Option<PyResult<PyRef<PyFloat>>> {
93 if let Some(float) = self.downcast_ref_if_exact::<PyFloat>(vm) {

Callers 15

field_size_limitFunction · 0.80
try_from_objectMethod · 0.80
already_warnedFunction · 0.80
get_filterFunction · 0.80
call_function_internalFunction · 0.80
process_fieldsMethod · 0.80
getitem_by_sliceMethod · 0.80
in_dllMethod · 0.80
value_to_bytesMethod · 0.80

Calls 13

intMethod · 0.80
numberMethod · 0.80
try_index_optMethod · 0.80
get_special_methodMethod · 0.80
try_indexMethod · 0.80
trimMethod · 0.80
warnFunction · 0.50
ErrClass · 0.50
to_ownedMethod · 0.45
invokeMethod · 0.45
as_bytesMethod · 0.45
as_wtf8Method · 0.45

Tested by

no test coverage detected