Debian Codegraph @

internal/visited/visited.go

raw
1 // Copyright (c) 2019, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package visited
8
9 import (
10 "reflect"
11 )
12
13 // visitKey is used by ctxerr.Context and its Visited map to handle
14 // cyclic references.
15 type visitedKey struct {
16 a1 uintptr
17 a2 uintptr
18 typ reflect.Type
19 }
20
21 // Visited allows to remember couples of same type pointers, typically
22 // not to do the same action twice if the couple has already been seen.
23 type Visited map[visitedKey]bool
24
25 // NewVisited returns a new [Visited] instance.
26 func NewVisited() Visited {
27 return Visited{}
28 }
29
30 // Record checks and, if needed, records a new entry for (got,
31 // expected) couple. It returns true if got & expected are pointers
32 // and have already been seen together. It returns false otherwise.
33 // It is the caller responsibility to check that got and expected
34 // types are the same.
35 func (v Visited) Record(got, expected reflect.Value) bool {
36 var addr1, addr2 uintptr
37 switch got.Kind() {
38 // Pointer() can not be used for interfaces and for slices the
39 // returned address is the array behind the slice, use UnsafeAddr()
40 // instead
41 case reflect.Slice, reflect.Interface:
42 if got.IsNil() || expected.IsNil() ||
43 !got.CanAddr() || !expected.CanAddr() {
44 return false
45 }
46 addr1 = got.UnsafeAddr()
47 addr2 = expected.UnsafeAddr()
48
49 // For maps and pointers use Pointer() to automatically handle
50 // indirect pointers
51 case reflect.Map, reflect.Ptr:
52 if got.IsNil() || expected.IsNil() {
53 return false
54 }
55 addr1 = got.Pointer()
56 addr2 = expected.Pointer()
57
58 default:
59 return false
60 }
61
62 if addr1 > addr2 {
63 // Canonicalize order to reduce number of entries in v.
64 // Assumes non-moving garbage collector.
65 addr1, addr2 = addr2, addr1
66 }
67
68 k := visitedKey{
69 a1: addr1,
70 a2: addr2,
71 typ: got.Type(),
72 }
73 if v[k] {
74 return true // references already seen
75 }
76
77 // Remember for later.
78 v[k] = true
79 return false
80 }