-
Notifications
You must be signed in to change notification settings - Fork 0
/
equal.go
72 lines (64 loc) · 1.23 KB
/
equal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright © 2020 David Arnold <dar@xoe.solutions>
// SPDX-License-Identifier: MIT
package generator
import (
. "github.com/dave/jennifer/jen"
"log"
)
type EqualFld struct {
Field QualField
IsDeepEqual bool
}
func GenEqual(f *File, typ string, flds []EqualFld) {
log.Printf("%s: generating '%s()'\n", typ, Equal)
f.Commentf("%s answers whether v is equivalent to %s", Equal, shortForm(typ))
f.Commentf("Always returns false if v is not a %s", typ)
f.Func().Params(
Id(shortForm(typ)).Id(typ),
).Id(
Equal,
).Params(
Id("v").Interface(),
).Bool().BlockFunc(func(g *Group) {
g.List(
Id("other"),
Id("ok"),
).Op(":=").Id("v").Assert(Id(typ))
g.If(
Op("!").Id("ok"),
).Block(
Return(
Id("false"),
),
)
for _, fld := range flds {
field := fld.Field
if fld.IsDeepEqual {
g.If(
Op("!").Qual(
"reflect",
"DeepEqual",
).Call(
Id(shortForm(typ)).Dot(field.Id),
Id("other").Dot(field.Id),
).Block(
Return(
Id("false"),
),
),
)
} else {
g.If(
Id(shortForm(typ)).Dot(field.Id).Op("!=").Id("other").Dot(field.Id),
).Block(
Return(
Id("false"),
),
)
}
}
g.Return(
Id("true"),
)
})
}