11package assert
22
33import (
4+ "math"
45 "reflect"
56 "testing"
67)
@@ -47,7 +48,10 @@ func isEqual(x, y any) bool {
4748 }
4849 v1 := reflect .ValueOf (x )
4950 v2 := reflect .ValueOf (y )
50- if ! isSameType (v1 .Type (), v2 .Type ()) {
51+ if isSame , isMixSign := isSameType (v1 .Type (), v2 .Type ()); ! isSame {
52+ if isMixSign {
53+ return isEqualForMixSignInt (v1 , v2 )
54+ }
5155 return false
5256 }
5357
@@ -68,6 +72,25 @@ func isEqual(x, y any) bool {
6872 }
6973}
7074
75+ // isEqualForMixSignInt checks the equality of two integers one of an integer is signed, but
76+ // another one is unsigned.
77+ func isEqualForMixSignInt (v1 , v2 reflect.Value ) bool {
78+ intVal := v1
79+ uintVal := v2
80+ if v1 .Kind () >= reflect .Uint && v1 .Kind () <= reflect .Uintptr {
81+ intVal = v2
82+ uintVal = v1
83+ }
84+
85+ if intVal .Int () < 0 {
86+ return false
87+ } else if uintVal .Uint () > uint64 (math .MaxInt64 ) {
88+ return false
89+ }
90+
91+ return intVal .Int () == int64 (uintVal .Uint ())
92+ }
93+
7194// isNil checks whether a value is nil or not. It'll always return false if the value is not a
7295// channel, a function, a map, a point, an unsafe point, an interface, or a slice.
7396func isNil (val any ) bool {
@@ -102,21 +125,26 @@ func isPanic(fn func()) (err any) {
102125
103126// isSameType indicates the equality of two types, and it will ignore the bit size of the same
104127// type. For example, `int32` and `int64` will be the same type.
105- func isSameType (t1 , t2 reflect.Type ) bool {
128+ //
129+ // It will returns a bool value to tell the callee function that one of the values is an integer,
130+ // but another one is unsigned. For this case, it needs to check the value to compare them.
131+ func isSameType (t1 , t2 reflect.Type ) (isSame bool , isMixSign bool ) {
106132 kind := t2 .Kind ()
107133
108134 switch t1 .Kind () {
109135 case reflect .Int , reflect .Int8 , reflect .Int16 , reflect .Int32 , reflect .Int64 :
110- return kind >= reflect .Int && kind <= reflect .Int64
136+ return kind >= reflect .Int && kind <= reflect .Int64 ,
137+ kind >= reflect .Uint && kind <= reflect .Uintptr
111138 case reflect .Uint , reflect .Uint8 , reflect .Uint16 , reflect .Uint32 , reflect .Uint64 ,
112139 reflect .Uintptr :
113- return kind >= reflect .Uint && kind <= reflect .Uintptr
140+ return kind >= reflect .Uint && kind <= reflect .Uintptr ,
141+ kind >= reflect .Int && kind <= reflect .Int64
114142 case reflect .Float32 , reflect .Float64 :
115- return kind == reflect .Float32 || kind == reflect .Float64
143+ return kind == reflect .Float32 || kind == reflect .Float64 , false
116144 case reflect .Complex64 , reflect .Complex128 :
117- return kind == reflect .Complex64 || kind == reflect .Complex128
145+ return kind == reflect .Complex64 || kind == reflect .Complex128 , false
118146 default :
119- return t1 == t2
147+ return t1 == t2 , false
120148 }
121149}
122150
0 commit comments