Skip to content

Commit f9ab272

Browse files
Add conversions for all primitive ints
1 parent ecc92ff commit f9ab272

File tree

1 file changed

+43
-23
lines changed

1 file changed

+43
-23
lines changed

vm/src/obj/objint.rs

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use num_integer::Integer;
55
use num_traits::{Pow, Signed, ToPrimitive, Zero};
66

77
use crate::format::FormatSpec;
8+
use crate::function::PyRef;
89
use crate::pyobject::{
910
FromPyObjectRef, IntoPyObject, PyContext, PyFuncArgs, PyObject, PyObjectPayload,
1011
PyObjectPayload2, PyObjectRef, PyResult, TryFromObject, TypeProtocol,
@@ -21,6 +22,8 @@ pub struct PyInt {
2122
pub value: BigInt,
2223
}
2324

25+
pub type PyIntRef = PyRef<PyInt>;
26+
2427
impl PyInt {
2528
pub fn new<T: ToBigInt>(i: T) -> Self {
2629
PyInt {
@@ -35,31 +38,48 @@ impl PyObjectPayload2 for PyInt {
3538
}
3639
}
3740

38-
impl IntoPyObject for usize {
39-
fn into_pyobject(self, ctx: &PyContext) -> PyResult {
40-
Ok(ctx.new_int(self))
41-
}
42-
}
43-
44-
impl TryFromObject for usize {
45-
fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
46-
// FIXME: don't use get_value
47-
match get_value(&obj).to_usize() {
48-
Some(value) => Ok(value),
49-
None => Err(vm.new_overflow_error("Int value cannot fit into Rust usize".to_string())),
41+
macro_rules! impl_into_pyobject_int {
42+
($($t:ty)*) => {$(
43+
impl IntoPyObject for $t {
44+
fn into_pyobject(self, ctx: &PyContext) -> PyResult {
45+
Ok(ctx.new_int(self))
46+
}
5047
}
51-
}
52-
}
53-
54-
impl TryFromObject for isize {
55-
fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
56-
// FIXME: don't use get_value
57-
match get_value(&obj).to_isize() {
58-
Some(value) => Ok(value),
59-
None => Err(vm.new_overflow_error("Int value cannot fit into Rust isize".to_string())),
48+
)*};
49+
}
50+
51+
impl_into_pyobject_int!(isize i8 i16 i32 i64 usize u8 u16 u32 u64) ;
52+
53+
macro_rules! impl_try_from_object_int {
54+
($(($t:ty, $to_prim:ident),)*) => {$(
55+
impl TryFromObject for $t {
56+
fn try_from_object(vm: &mut VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
57+
match PyRef::<PyInt>::try_from_object(vm, obj)?.value.$to_prim() {
58+
Some(value) => Ok(value),
59+
None => Err(
60+
vm.new_overflow_error(concat!(
61+
"Int value cannot fit into Rust ",
62+
stringify!($t)
63+
).to_string())
64+
),
65+
}
66+
}
6067
}
61-
}
62-
}
68+
)*};
69+
}
70+
71+
impl_try_from_object_int!(
72+
(isize, to_isize),
73+
(i8, to_i8),
74+
(i16, to_i16),
75+
(i32, to_i32),
76+
(i64, to_i64),
77+
(usize, to_usize),
78+
(u8, to_u8),
79+
(u16, to_u16),
80+
(u32, to_u32),
81+
(u64, to_u64),
82+
);
6383

6484
fn int_repr(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
6585
arg_check!(vm, args, required = [(int, Some(vm.ctx.int_type()))]);

0 commit comments

Comments
 (0)