diff --git a/semantic/deep_equal.go b/semantic/deep_equal.go new file mode 100644 index 00000000..2f56974c --- /dev/null +++ b/semantic/deep_equal.go @@ -0,0 +1,30 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package semantic + +import ( + "k8s.io/utils/third_party/forked/golang/reflect" +) + +// Equalities is a map from type to a function comparing two values of +// that type. +type Equalities = reflect.Equalities + +// EqualitiesOrDie adds the given funcs and panics on any error. +func EqualitiesOrDie(funcs ...interface{}) Equalities { + return reflect.EqualitiesOrDie(funcs...) +} diff --git a/semantic/deep_equal_test.go b/semantic/deep_equal_test.go new file mode 100644 index 00000000..902dd2f9 --- /dev/null +++ b/semantic/deep_equal_test.go @@ -0,0 +1,31 @@ +/* +Copyright 2019 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package semantic + +import ( + "testing" +) + +var mod2Equal = EqualitiesOrDie(func(a, b int) bool { + return a%2 == b%2 +}) + +func TestEqualities(t *testing.T) { + if !mod2Equal.DeepEqual(3, 5) { + t.Error("expected 3 and 5 to be equal mod 2") + } +} diff --git a/third_party/forked/golang/LICENSE b/third_party/forked/golang/LICENSE new file mode 100644 index 00000000..74487567 --- /dev/null +++ b/third_party/forked/golang/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/third_party/forked/golang/PATENTS b/third_party/forked/golang/PATENTS new file mode 100644 index 00000000..73309904 --- /dev/null +++ b/third_party/forked/golang/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/third_party/forked/golang/reflect/README.md b/third_party/forked/golang/reflect/README.md new file mode 100644 index 00000000..ed76cfc6 --- /dev/null +++ b/third_party/forked/golang/reflect/README.md @@ -0,0 +1,6 @@ +This was originally forked from https://github.com/golang/go/blob/master/src/reflect/deepequal.go in order to + +- consider empty lists and empty maps equal to their nil counterparts +- add a `AddFuncs` mechanism to add custom equality funcs for specific types. + +Meanwhile it has diverged quite a lot while still following the original algorithm at the core though. diff --git a/third_party/forked/golang/reflect/deep_equal.go b/third_party/forked/golang/reflect/deep_equal.go new file mode 100644 index 00000000..2b5a3503 --- /dev/null +++ b/third_party/forked/golang/reflect/deep_equal.go @@ -0,0 +1,398 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package reflect is a fork of go's standard library reflection package, which +// allows for deep equal with equality functions defined. +package reflect + +import ( + "fmt" + "reflect" + "strings" +) + +// Equalities is a map from type to a function comparing two values of +// that type. +type Equalities map[reflect.Type]reflect.Value + +// EqualitiesOrDie adds the given funcs and panics on any error. +func EqualitiesOrDie(funcs ...interface{}) Equalities { + e := Equalities{} + if err := e.AddFuncs(funcs...); err != nil { + panic(err) + } + return e +} + +// AddFuncs is a shortcut for multiple calls to AddFunc. +func (e Equalities) AddFuncs(funcs ...interface{}) error { + for _, f := range funcs { + if err := e.AddFunc(f); err != nil { + return err + } + } + return nil +} + +// AddFunc uses func as an equality function: it must take +// two parameters of the same type, and return a boolean. +func (e Equalities) AddFunc(eqFunc interface{}) error { + fv := reflect.ValueOf(eqFunc) + ft := fv.Type() + if ft.Kind() != reflect.Func { + return fmt.Errorf("expected func, got: %v", ft) + } + if ft.NumIn() != 2 { + return fmt.Errorf("expected two 'in' params, got: %v", ft) + } + if ft.NumOut() != 1 { + return fmt.Errorf("expected one 'out' param, got: %v", ft) + } + if ft.In(0) != ft.In(1) { + return fmt.Errorf("expected arg 1 and 2 to have same type, but got %v", ft) + } + var forReturnType bool + boolType := reflect.TypeOf(forReturnType) + if ft.Out(0) != boolType { + return fmt.Errorf("expected bool return, got: %v", ft) + } + e[ft.In(0)] = fv + return nil +} + +// Below here is forked from go's reflect/deepequal.go + +// During deepValueEqual, must keep track of checks that are +// in progress. The comparison algorithm assumes that all +// checks in progress are true when it reencounters them. +// Visited comparisons are stored in a map indexed by visit. +type visit struct { + a1 uintptr + a2 uintptr + typ reflect.Type +} + +// unexportedTypePanic is thrown when you use this DeepEqual on something that has an +// unexported type. It indicates a programmer error, so should not occur at runtime, +// which is why it's not public and thus impossible to catch. +type unexportedTypePanic []reflect.Type + +func (u unexportedTypePanic) Error() string { return u.String() } +func (u unexportedTypePanic) String() string { + strs := make([]string, len(u)) + for i, t := range u { + strs[i] = fmt.Sprintf("%v", t) + } + return "an unexported field was encountered, nested like this: " + strings.Join(strs, " -> ") +} + +func makeUsefulPanic(v reflect.Value) { + if x := recover(); x != nil { + if u, ok := x.(unexportedTypePanic); ok { + u = append(unexportedTypePanic{v.Type()}, u...) + x = u + } + panic(x) + } +} + +// deepValueEqual tests for deep equality using reflected types. The map argument tracks +// comparisons that have already been seen, which allows short circuiting on +// recursive types. +func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool { + defer makeUsefulPanic(v1) + + if !v1.IsValid() || !v2.IsValid() { + return v1.IsValid() == v2.IsValid() + } + if v1.Type() != v2.Type() { + return false + } + if fv, ok := e[v1.Type()]; ok { + return fv.Call([]reflect.Value{v1, v2})[0].Bool() + } + if v1.CanAddr() { + if fv, ok := e[v1.Addr().Type()]; ok { + return fv.Call([]reflect.Value{v1.Addr(), v2.Addr()})[0].Bool() + } + } + + hard := func(k reflect.Kind) bool { + switch k { + case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: + return true + } + return false + } + + if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { + addr1 := v1.UnsafeAddr() + addr2 := v2.UnsafeAddr() + if addr1 > addr2 { + // Canonicalize order to reduce number of entries in visited. + addr1, addr2 = addr2, addr1 + } + + // Short circuit if references are identical ... + if addr1 == addr2 { + return true + } + + // ... or already seen + typ := v1.Type() + v := visit{addr1, addr2, typ} + if visited[v] { + return true + } + + // Remember for later. + visited[v] = true + } + + switch v1.Kind() { + case reflect.Array: + // We don't need to check length here because length is part of + // an array's type, which has already been filtered for. + for i := 0; i < v1.Len(); i++ { + if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) { + return false + } + } + return true + case reflect.Slice: + if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { + return false + } + if v1.IsNil() || v1.Len() == 0 { + return true + } + if v1.Len() != v2.Len() { + return false + } + if v1.Pointer() == v2.Pointer() { + return true + } + for i := 0; i < v1.Len(); i++ { + if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) { + return false + } + } + return true + case reflect.Interface: + if v1.IsNil() || v2.IsNil() { + return v1.IsNil() == v2.IsNil() + } + return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1) + case reflect.Ptr: + return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1) + case reflect.Struct: + for i, n := 0, v1.NumField(); i < n; i++ { + if !e.deepValueEqual(v1.Field(i), v2.Field(i), visited, depth+1) { + return false + } + } + return true + case reflect.Map: + if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { + return false + } + if v1.IsNil() || v1.Len() == 0 { + return true + } + if v1.Len() != v2.Len() { + return false + } + if v1.Pointer() == v2.Pointer() { + return true + } + for _, k := range v1.MapKeys() { + if !e.deepValueEqual(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) { + return false + } + } + return true + case reflect.Func: + if v1.IsNil() && v2.IsNil() { + return true + } + // Can't do better than this: + return false + default: + // Normal equality suffices + if !v1.CanInterface() || !v2.CanInterface() { + panic(unexportedTypePanic{}) + } + return v1.Interface() == v2.Interface() + } +} + +// DeepEqual is like reflect.DeepEqual, but focused on semantic equality +// instead of memory equality. +// +// It will use e's equality functions if it finds types that match. +// +// An empty slice *is* equal to a nil slice for our purposes; same for maps. +// +// Unexported field members cannot be compared and will cause an imformative panic; you must add an Equality +// function for these types. +func (e Equalities) DeepEqual(a1, a2 interface{}) bool { + if a1 == nil || a2 == nil { + return a1 == a2 + } + v1 := reflect.ValueOf(a1) + v2 := reflect.ValueOf(a2) + if v1.Type() != v2.Type() { + return false + } + return e.deepValueEqual(v1, v2, make(map[visit]bool), 0) +} + +func (e Equalities) deepValueDerive(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool { + defer makeUsefulPanic(v1) + + if !v1.IsValid() || !v2.IsValid() { + return v1.IsValid() == v2.IsValid() + } + if v1.Type() != v2.Type() { + return false + } + if fv, ok := e[v1.Type()]; ok { + return fv.Call([]reflect.Value{v1, v2})[0].Bool() + } + if v1.CanAddr() { + if fv, ok := e[v1.Addr().Type()]; ok { + return fv.Call([]reflect.Value{v1.Addr(), v2.Addr()})[0].Bool() + } + } + + hard := func(k reflect.Kind) bool { + switch k { + case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: + return true + } + return false + } + + if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { + addr1 := v1.UnsafeAddr() + addr2 := v2.UnsafeAddr() + if addr1 > addr2 { + // Canonicalize order to reduce number of entries in visited. + addr1, addr2 = addr2, addr1 + } + + // Short circuit if references are identical ... + if addr1 == addr2 { + return true + } + + // ... or already seen + typ := v1.Type() + v := visit{addr1, addr2, typ} + if visited[v] { + return true + } + + // Remember for later. + visited[v] = true + } + + switch v1.Kind() { + case reflect.Array: + // We don't need to check length here because length is part of + // an array's type, which has already been filtered for. + for i := 0; i < v1.Len(); i++ { + if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { + return false + } + } + return true + case reflect.Slice: + if v1.IsNil() || v1.Len() == 0 { + return true + } + if v1.Len() > v2.Len() { + return false + } + if v1.Pointer() == v2.Pointer() { + return true + } + for i := 0; i < v1.Len(); i++ { + if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { + return false + } + } + return true + case reflect.String: + if v1.Len() == 0 { + return true + } + if v1.Len() > v2.Len() { + return false + } + return v1.String() == v2.String() + case reflect.Interface: + if v1.IsNil() { + return true + } + return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) + case reflect.Ptr: + if v1.IsNil() { + return true + } + return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) + case reflect.Struct: + for i, n := 0, v1.NumField(); i < n; i++ { + if !e.deepValueDerive(v1.Field(i), v2.Field(i), visited, depth+1) { + return false + } + } + return true + case reflect.Map: + if v1.IsNil() || v1.Len() == 0 { + return true + } + if v1.Len() > v2.Len() { + return false + } + if v1.Pointer() == v2.Pointer() { + return true + } + for _, k := range v1.MapKeys() { + if !e.deepValueDerive(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) { + return false + } + } + return true + case reflect.Func: + if v1.IsNil() && v2.IsNil() { + return true + } + // Can't do better than this: + return false + default: + // Normal equality suffices + if !v1.CanInterface() || !v2.CanInterface() { + panic(unexportedTypePanic{}) + } + return v1.Interface() == v2.Interface() + } +} + +// DeepDerivative is similar to DeepEqual except that unset fields in a1 are +// ignored (not compared). This allows us to focus on the fields that matter to +// the semantic comparison. +// +// The unset fields include a nil pointer and an empty string. +func (e Equalities) DeepDerivative(a1, a2 interface{}) bool { + if a1 == nil { + return true + } + v1 := reflect.ValueOf(a1) + v2 := reflect.ValueOf(a2) + if v1.Type() != v2.Type() { + return false + } + return e.deepValueDerive(v1, v2, make(map[visit]bool), 0) +} diff --git a/third_party/forked/golang/reflect/deep_equal_test.go b/third_party/forked/golang/reflect/deep_equal_test.go new file mode 100644 index 00000000..4a062993 --- /dev/null +++ b/third_party/forked/golang/reflect/deep_equal_test.go @@ -0,0 +1,137 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package reflect + +import ( + "testing" +) + +func TestEqualities(t *testing.T) { + e := Equalities{} + type Bar struct { + X int + } + type Baz struct { + Y Bar + } + err := e.AddFuncs( + func(a, b int) bool { + return a+1 == b + }, + func(a, b Bar) bool { + return a.X*10 == b.X + }, + ) + if err != nil { + t.Fatalf("Unexpected: %v", err) + } + + type Foo struct { + X int + } + + table := []struct { + a, b interface{} + equal bool + }{ + {1, 2, true}, + {2, 1, false}, + {"foo", "fo", false}, + {"foo", "foo", true}, + {"foo", "foobar", false}, + {Foo{1}, Foo{2}, true}, + {Foo{2}, Foo{1}, false}, + {Bar{1}, Bar{10}, true}, + {&Bar{1}, &Bar{10}, true}, + {Baz{Bar{1}}, Baz{Bar{10}}, true}, + {[...]string{}, [...]string{"1", "2", "3"}, false}, + {[...]string{"1"}, [...]string{"1", "2", "3"}, false}, + {[...]string{"1", "2", "3"}, [...]string{}, false}, + {[...]string{"1", "2", "3"}, [...]string{"1", "2", "3"}, true}, + {map[string]int{"foo": 1}, map[string]int{}, false}, + {map[string]int{"foo": 1}, map[string]int{"foo": 2}, true}, + {map[string]int{"foo": 2}, map[string]int{"foo": 1}, false}, + {map[string]int{"foo": 1}, map[string]int{"foo": 2, "bar": 6}, false}, + {map[string]int{"foo": 1, "bar": 6}, map[string]int{"foo": 2}, false}, + {map[string]int{}, map[string]int(nil), true}, + {[]string(nil), []string(nil), true}, + {[]string{}, []string(nil), true}, + {[]string(nil), []string{}, true}, + {[]string{"1"}, []string(nil), false}, + {[]string{}, []string{"1", "2", "3"}, false}, + {[]string{"1"}, []string{"1", "2", "3"}, false}, + {[]string{"1", "2", "3"}, []string{}, false}, + } + + for _, item := range table { + if e, a := item.equal, e.DeepEqual(item.a, item.b); e != a { + t.Errorf("Expected (%+v == %+v) == %v, but got %v", item.a, item.b, e, a) + } + } +} + +func TestDerivates(t *testing.T) { + e := Equalities{} + type Bar struct { + X int + } + type Baz struct { + Y Bar + } + err := e.AddFuncs( + func(a, b int) bool { + return a+1 == b + }, + func(a, b Bar) bool { + return a.X*10 == b.X + }, + ) + if err != nil { + t.Fatalf("Unexpected: %v", err) + } + + type Foo struct { + X int + } + + table := []struct { + a, b interface{} + equal bool + }{ + {1, 2, true}, + {2, 1, false}, + {"foo", "fo", false}, + {"foo", "foo", true}, + {"foo", "foobar", false}, + {Foo{1}, Foo{2}, true}, + {Foo{2}, Foo{1}, false}, + {Bar{1}, Bar{10}, true}, + {&Bar{1}, &Bar{10}, true}, + {Baz{Bar{1}}, Baz{Bar{10}}, true}, + {[...]string{}, [...]string{"1", "2", "3"}, false}, + {[...]string{"1"}, [...]string{"1", "2", "3"}, false}, + {[...]string{"1", "2", "3"}, [...]string{}, false}, + {[...]string{"1", "2", "3"}, [...]string{"1", "2", "3"}, true}, + {map[string]int{"foo": 1}, map[string]int{}, false}, + {map[string]int{"foo": 1}, map[string]int{"foo": 2}, true}, + {map[string]int{"foo": 2}, map[string]int{"foo": 1}, false}, + {map[string]int{"foo": 1}, map[string]int{"foo": 2, "bar": 6}, true}, + {map[string]int{"foo": 1, "bar": 6}, map[string]int{"foo": 2}, false}, + {map[string]int{}, map[string]int(nil), true}, + {[]string(nil), []string(nil), true}, + {[]string{}, []string(nil), true}, + {[]string(nil), []string{}, true}, + {[]string{"1"}, []string(nil), false}, + {[]string{}, []string{"1", "2", "3"}, true}, + {[]string{"1"}, []string{"1", "2", "3"}, true}, + {[]string{"1", "2", "3"}, []string{}, false}, + } + + for _, item := range table { + if e, a := item.equal, e.DeepDerivative(item.a, item.b); e != a { + t.Errorf("Expected (%+v ~ %+v) == %v, but got %v", item.a, item.b, e, a) + } + } +}