Debian Codegraph @

equalcheck.go

raw symbols SCIP
1 package check
2
3 import (
4 "sync"
5
6 "github.com/powerman/check/internal/deepequal"
7 )
8
9 //nolint:gochecknoglobals // Registry of custom equal checkers.
10 var (
11 equalCheckersMu sync.RWMutex
12 equalCheckers []EqualChecker
13 )
14
15 // EqualChecker compares two values for DeepEqual/NotDeepEqual.
16 // ok=false means "this checker does not apply to this pair"
17 // and the next registered checker (then the built-in logic) is consulted.
18 type EqualChecker func(actual, expected any) (equal, ok bool)
19
20 // ResetEqualCheckers removes all registered equal checkers.
21 //
22 // Combine with RegisterEqualChecker to define a custom chain in a specific order.
23 //
24 // Intended for TestMain.
25 // Not safe to call concurrently with running checks.
26 func ResetEqualCheckers() {
27 equalCheckersMu.Lock()
28 defer equalCheckersMu.Unlock()
29 equalCheckers = nil
30 }
31
32 // RegisterEqualChecker adds a custom equal comparison strategy
33 // used by DeepEqual and NotDeepEqual.
34 // Checkers run in registration order before built-in logic.
35 //
36 // Intended to be called from init() or TestMain.
37 // Not safe to call concurrently with running checks.
38 func RegisterEqualChecker(f EqualChecker) {
39 equalCheckersMu.Lock()
40 defer equalCheckersMu.Unlock()
41 equalCheckers = append(equalCheckers, f)
42 }
43
44 // runEqualCheckers iterates registered checkers with the original actual/expected values.
45 // Returns (equal, ok) where ok=true means a checker claimed this pair.
46 func runEqualCheckers(actual, expected any) (equal, ok bool) {
47 equalCheckersMu.RLock()
48 defer equalCheckersMu.RUnlock()
49 for _, check := range equalCheckers {
50 if eq, claimed := check(actual, expected); claimed {
51 return eq, true
52 }
53 }
54 return false, false
55 }
56
57 // elemEqual reports whether a and b are equal for element/value comparison
58 // (used by SortEqual and Subset): registered EqualCheckers run first,
59 // falling back to [deepequal.DeepEqual], exactly like DeepEqual/NotDeepEqual do.
60 func elemEqual(a, b any) bool {
61 equal, claimed := runEqualCheckers(a, b)
62 if !claimed {
63 if hasMethod(a, "ProtoReflect") || hasMethod(b, "ProtoReflect") {
64 panic("check: protobuf message detected; " +
65 "import github.com/powerman/checkproto to compare protobuf messages")
66 }
67 equal = deepequal.DeepEqual(a, b)
68 }
69 return equal
70 }