-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoverride.go
79 lines (68 loc) · 1.67 KB
/
override.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
73
74
75
76
77
78
79
package measure
import (
"encoding/json"
"sync/atomic"
)
// Override measure uses a default measure for all arcs that are not true for a
// condition. It uses an override measure for all arcs that are true for the
// condition.
func Override(
defaultByIndex ByIndex,
overrideByIndex ByIndex,
condition func(from, to int) bool,
) ByIndex {
return &override{
defaultByIndex: defaultByIndex,
overrideByIndex: overrideByIndex,
condition: condition,
}
}
// DebugOverride returns an Override that when marshalled will include debugging
// information describing the number of queries for default and override
// elements.
func DebugOverride(
defaultByIndex ByIndex,
overrideByIndex ByIndex,
condition func(from, to int) bool,
) ByIndex {
return &override{
defaultByIndex: defaultByIndex,
overrideByIndex: overrideByIndex,
condition: condition,
debugMode: true,
}
}
type override struct {
defaultByIndex ByIndex
overrideByIndex ByIndex
condition func(from, to int) bool
debugMode bool
defaultCount uint64
overrideCount uint64
}
func (o *override) Cost(from, to int) float64 {
if o.condition(from, to) {
if o.debugMode {
atomic.AddUint64(&o.overrideCount, 1)
}
return o.overrideByIndex.Cost(from, to)
}
if o.debugMode {
atomic.AddUint64(&o.defaultCount, 1)
}
return o.defaultByIndex.Cost(from, to)
}
func (o *override) MarshalJSON() ([]byte, error) {
output := map[string]any{
"default": o.defaultByIndex,
"override": o.overrideByIndex,
"type": "override",
}
if o.debugMode {
output["counts"] = map[string]uint64{
"default": o.defaultCount,
"override": o.overrideCount,
}
}
return json.Marshal(output)
}