(&self, vm: &VirtualMachine)
| 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) { |
no test coverage detected