@@ -5,6 +5,7 @@ use num_integer::Integer;
5
5
use num_traits:: { Pow , Signed , ToPrimitive , Zero } ;
6
6
7
7
use crate :: format:: FormatSpec ;
8
+ use crate :: function:: PyRef ;
8
9
use crate :: pyobject:: {
9
10
FromPyObjectRef , IntoPyObject , PyContext , PyFuncArgs , PyObject , PyObjectPayload ,
10
11
PyObjectPayload2 , PyObjectRef , PyResult , TryFromObject , TypeProtocol ,
@@ -21,6 +22,8 @@ pub struct PyInt {
21
22
pub value : BigInt ,
22
23
}
23
24
25
+ pub type PyIntRef = PyRef < PyInt > ;
26
+
24
27
impl PyInt {
25
28
pub fn new < T : ToBigInt > ( i : T ) -> Self {
26
29
PyInt {
@@ -35,31 +38,48 @@ impl PyObjectPayload2 for PyInt {
35
38
}
36
39
}
37
40
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
+ }
50
47
}
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
+ }
60
67
}
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
+ ) ;
63
83
64
84
fn int_repr ( vm : & mut VirtualMachine , args : PyFuncArgs ) -> PyResult {
65
85
arg_check ! ( vm, args, required = [ ( int, Some ( vm. ctx. int_type( ) ) ) ] ) ;
0 commit comments