2018-02-15 17:14:05 +08:00
|
|
|
package vals
|
2018-01-25 07:28:50 +08:00
|
|
|
|
2018-01-28 01:26:22 +08:00
|
|
|
import (
|
|
|
|
"reflect"
|
2018-01-29 22:36:43 +08:00
|
|
|
|
|
|
|
"github.com/xiaq/persistent/hashmap"
|
2018-01-28 01:26:22 +08:00
|
|
|
)
|
2018-01-25 07:57:58 +08:00
|
|
|
|
|
|
|
// Equaler wraps the Equal method.
|
|
|
|
type Equaler interface {
|
|
|
|
// Equal compares the receiver to another value. Two equal values must have
|
|
|
|
// the same hash code.
|
|
|
|
Equal(other interface{}) bool
|
|
|
|
}
|
|
|
|
|
2018-01-27 23:51:37 +08:00
|
|
|
// Equal returns whether two values are equal. It is implemented for the builtin
|
2018-01-29 22:36:43 +08:00
|
|
|
// types bool and string, and types satisfying the listEqualable, mapEqualable
|
|
|
|
// or Equaler interface. For other types, it uses reflect.DeepEqual to compare
|
|
|
|
// the two values.
|
2018-01-25 07:28:50 +08:00
|
|
|
func Equal(x, y interface{}) bool {
|
2018-01-25 09:40:15 +08:00
|
|
|
switch x := x.(type) {
|
2018-02-02 12:42:41 +08:00
|
|
|
case Equaler:
|
|
|
|
return x.Equal(y)
|
2018-01-27 23:51:37 +08:00
|
|
|
case bool:
|
|
|
|
return x == y
|
2018-01-25 09:40:15 +08:00
|
|
|
case string:
|
|
|
|
return x == y
|
2018-01-28 01:26:22 +08:00
|
|
|
case listEqualable:
|
2018-01-29 22:36:43 +08:00
|
|
|
if yy, ok := y.(listEqualable); ok {
|
|
|
|
return equalList(x, yy)
|
2018-01-28 01:26:22 +08:00
|
|
|
}
|
2018-01-29 22:36:43 +08:00
|
|
|
return false
|
|
|
|
case mapEqualable:
|
|
|
|
if yy, ok := y.(mapEqualable); ok {
|
|
|
|
return equalMap(x, yy)
|
2018-01-28 01:26:22 +08:00
|
|
|
}
|
2018-01-29 22:36:43 +08:00
|
|
|
return false
|
2018-01-25 07:57:58 +08:00
|
|
|
}
|
|
|
|
return reflect.DeepEqual(x, y)
|
2018-01-25 07:28:50 +08:00
|
|
|
}
|
2018-01-28 01:26:22 +08:00
|
|
|
|
|
|
|
type listEqualable interface {
|
|
|
|
Lener
|
|
|
|
listIterable
|
|
|
|
}
|
2018-01-29 22:36:43 +08:00
|
|
|
|
|
|
|
func equalList(x, y listEqualable) bool {
|
|
|
|
if x.Len() != y.Len() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ix := x.Iterator()
|
|
|
|
iy := y.Iterator()
|
|
|
|
for ix.HasElem() && iy.HasElem() {
|
|
|
|
if !Equal(ix.Elem(), iy.Elem()) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ix.Next()
|
|
|
|
iy.Next()
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
type mapEqualable interface {
|
|
|
|
Lener
|
2018-03-02 07:15:51 +08:00
|
|
|
Index(interface{}) (interface{}, bool)
|
2018-01-29 22:36:43 +08:00
|
|
|
Iterator() hashmap.Iterator
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ mapEqualable = hashmap.Map(nil)
|
|
|
|
|
|
|
|
func equalMap(x, y mapEqualable) bool {
|
|
|
|
if x.Len() != y.Len() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for it := x.Iterator(); it.HasElem(); it.Next() {
|
|
|
|
k, vx := it.Elem()
|
2018-03-02 07:15:51 +08:00
|
|
|
vy, ok := y.Index(k)
|
2018-01-29 22:36:43 +08:00
|
|
|
if !ok || !Equal(vx, vy) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|