github.com/aristanetworks/gomap@v0.0.0-20240103001659-f6b0e31fb1a7/funcs_test.go (about) 1 // Modifications copyright (c) Arista Networks, Inc. 2022 2 // Underlying 3 // Copyright 2014 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package gomap 8 9 import ( 10 "bytes" 11 "hash/maphash" 12 "testing" 13 ) 14 15 func TestString(t *testing.T) { 16 m := New(bytes.Equal, maphash.Bytes, 17 KeyElem[[]byte, struct{}]{[]byte("abc"), struct{}{}}, 18 KeyElem[[]byte, struct{}]{[]byte("def"), struct{}{}}, 19 KeyElem[[]byte, struct{}]{[]byte("ghi"), struct{}{}}, 20 ) 21 s := m.String() 22 expected := "gomap.Map[[100 101 102]:{} [103 104 105]:{} [97 98 99]:{}]" 23 if expected != s { 24 t.Errorf("Got: %q Expected: %q", s, expected) 25 } 26 27 s = StringFunc(m, 28 func(b []byte) string { return string(b) }, 29 func(struct{}) string { return "✅" }) 30 expected = "gomap.Map[abc:✅ def:✅ ghi:✅]" 31 if s != expected { 32 t.Errorf("Got: %q Expected: %q", s, expected) 33 } 34 } 35 36 func TestEqual(t *testing.T) { 37 fromMap := func(m map[string]int) *Map[string, int] { 38 mm := NewHint[string, int](len(m), func(a, b string) bool { return a == b }, maphash.String) 39 for k, v := range m { 40 mm.Set(k, v) 41 } 42 return mm 43 } 44 45 for _, tc := range []struct { 46 a *Map[string, int] 47 b *Map[string, int] 48 equal bool 49 }{{ 50 a: nil, b: nil, equal: true, 51 }, { 52 a: fromMap(map[string]int{"a": 1}), b: nil, equal: false, 53 }, { 54 a: nil, b: fromMap(map[string]int{"a": 1}), equal: false, 55 }, { 56 a: fromMap(map[string]int{"a": 1}), 57 b: fromMap(map[string]int{"a": 1}), 58 equal: true, 59 }, { 60 a: fromMap(map[string]int{"a": 1, "b": 2}), 61 b: fromMap(map[string]int{"a": 1}), 62 equal: false, 63 }, { 64 a: fromMap(map[string]int{"a": 1, "b": 2}), 65 b: fromMap(map[string]int{"a": 1, "b": 3}), 66 equal: false, 67 }, { 68 a: fromMap(map[string]int{"a": 1, "b": 2}), 69 b: fromMap(map[string]int{"a": 1, "c": 3}), 70 equal: false, 71 }} { 72 t.Run(tc.a.String()+tc.b.String(), func(t *testing.T) { 73 if got := Equal(tc.a, tc.b); got != tc.equal { 74 t.Errorf("Equal: %t Exp: %t", got, tc.equal) 75 } 76 if got := EqualFunc(tc.a, tc.b, func(x, y int) bool { return x == y }); got != tc.equal { 77 t.Errorf("EqualFunc: %t Exp: %t", got, tc.equal) 78 } 79 }) 80 } 81 } 82 83 func BenchmarkStringFunc(b *testing.B) { 84 m := New(bytes.Equal, maphash.Bytes, 85 KeyElem[[]byte, struct{}]{[]byte("abc"), struct{}{}}, 86 KeyElem[[]byte, struct{}]{[]byte("def"), struct{}{}}, 87 KeyElem[[]byte, struct{}]{[]byte("ghi"), struct{}{}}, 88 ) 89 b.ReportAllocs() 90 b.ResetTimer() 91 for i := 0; i < b.N; i++ { 92 StringFunc(m, 93 func(b []byte) string { return string(b) }, 94 func(struct{}) string { return "x" }) 95 } 96 }