Refactoring int.inner_xshift methods.
@@ -166,33 +166,13 @@ fn inner_divmod(int1: &PyInt, int2: &PyInt, vm: &VirtualMachine) -> PyResult {
}
fn inner_lshift(int1: &PyInt, int2: &PyInt, vm: &VirtualMachine) -> PyResult {
- if let Some(n_bits) = int2.value.to_usize() {
- return Ok(vm.ctx.new_int(&int1.value << n_bits));
- }
-
- // i2 failed `to_usize()` conversion
- match &int2.value {
- v if *v < BigInt::zero() => Err(vm.new_value_error("negative shift count".to_string())),
- v if *v > BigInt::from(usize::max_value()) => {
- Err(vm.new_overflow_error("the number is too large to convert to int".to_string()))
- }
- _ => panic!("Failed converting {} to rust usize", int2.value),
- }
+ let n_bits = get_shift_amount(int2, vm)?;
+ Ok(vm.ctx.new_int(&int1.value << n_bits))
}
fn inner_rshift(int1: &PyInt, int2: &PyInt, vm: &VirtualMachine) -> PyResult {
- if let Some(n_bits) = int2.value.to_usize() {
- return Ok(vm.ctx.new_int(&int1.value >> n_bits));
- }
-
- // i2 failed `to_usize()` conversion
- match &int2.value {
- v if *v < BigInt::zero() => Err(vm.new_value_error("negative shift count".to_string())),
- v if *v > BigInt::from(usize::max_value()) => {
- Err(vm.new_overflow_error("the number is too large to convert to int".to_string()))
- }
- _ => panic!("Failed converting {} to rust usize", int2.value),
- }
+ let n_bits = get_shift_amount(int2, vm)?;
+ Ok(vm.ctx.new_int(&int1.value >> n_bits))
}
#[pyimpl]
@@ -805,6 +785,20 @@ fn div_ints(vm: &VirtualMachine, i1: &BigInt, i2: &BigInt) -> PyResult {
}
}
+fn get_shift_amount(amount: &PyInt, vm: &VirtualMachine) -> PyResult<usize> {
+ if let Some(n_bits) = amount.value.to_usize() {
+ Ok(n_bits)
+ } else {
+ match &amount.value {
+ v if *v < BigInt::zero() => Err(vm.new_value_error("negative shift count".to_string())),
+ v if *v > BigInt::from(usize::max_value()) => {
+ Err(vm.new_overflow_error("the number is too large to convert to int".to_string()))
+ }
+ _ => panic!("Failed converting {} to rust usize", amount.value),
+ }
+ }
+}
+
pub fn init(context: &PyContext) {
PyInt::extend_class(context, &context.int_type);
extend_class!(context, &context.int_type, {
