Debian Codegraph @

internal/anchors/types.go

raw
1 // Copyright (c) 2020, 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 anchors
8
9 import (
10 "errors"
11 "fmt"
12 "math"
13 "reflect"
14 "time"
15
16 "github.com/maxatome/go-testdeep/internal/types"
17 )
18
19 type anchorableType struct {
20 typ reflect.Type
21 builder reflect.Value
22 }
23
24 // AnchorableTypes contains all non-native types that can be
25 // anchorable. See [AddAnchorableStructType] to add a new type to it.
26 var AnchorableTypes []anchorableType
27
28 func init() {
29 AddAnchorableStructType(func(nextAnchor int) time.Time { //nolint: errcheck
30 return time.Unix(math.MaxInt64-1000424443-int64(nextAnchor), 42)
31 })
32 }
33
34 // AddAnchorableStructType declares a struct type as anchorable. fn
35 // is a function allowing to return a unique and identifiable instance
36 // of the struct type.
37 //
38 // fn has to have the following signature:
39 //
40 // func (nextAnchor int) TYPE
41 //
42 // TYPE is the struct type to make anchorable and nextAnchor is an
43 // index to allow to differentiate several instances of the same type.
44 //
45 // For example, the [time.Time] type which is anchorable by default,
46 // is declared as:
47 //
48 // AddAnchorableStructType(func (nextAnchor int) time.Time {
49 // return time.Unix(math.MaxInt64-1000424443-int64(nextAnchor), 42)
50 // })
51 //
52 // Just as a note, the 1000424443 constant allows to avoid to flirt
53 // with the [math.MaxInt64] extreme limit and so avoid possible
54 // collision with real world values.
55 //
56 // It returns an error if the provided fn is not a function or if it
57 // has not the expected signature (see above).
58 func AddAnchorableStructType(fn any) error {
59 vfn := reflect.ValueOf(fn)
60
61 if vfn.Kind() == reflect.Func {
62 fnType := vfn.Type()
63
64 if !fnType.IsVariadic() &&
65 fnType.NumIn() == 1 && fnType.NumOut() == 1 &&
66 fnType.In(0) == types.Int &&
67 fnType.Out(0).Kind() == reflect.Struct {
68 typ := fnType.Out(0)
69 if !typ.Comparable() {
70 return fmt.Errorf(
71 "type %s is not comparable, it cannot be anchorable", typ)
72 }
73
74 for i, at := range AnchorableTypes {
75 if at.typ == typ {
76 AnchorableTypes[i].builder = vfn
77 return nil
78 }
79 }
80
81 AnchorableTypes = append(AnchorableTypes, anchorableType{
82 typ: typ,
83 builder: vfn,
84 })
85 return nil
86 }
87 }
88
89 return errors.New("usage: AddAnchorableStructType(func (nextAnchor int) STRUCT_TYPE)")
90 }