-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtoposort.go
99 lines (90 loc) · 2.12 KB
/
toposort.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2018 GRAIL, Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package infra
type state int
const (
todo state = iota
visiting
visited
)
// TopoSorter implements a simple topological sort
// based on provider instances.
type topoSorter map[*instance][]*instance
// Add adds an edge to the graph s. If the destination edge is
// nil, Add simply adds the node from to the graph.
func (s topoSorter) Add(from, to *instance) {
if to != nil {
s[from] = append(s[from], to)
return
}
if _, ok := s[from]; ok {
return
}
s[from] = nil
}
// Sort returns a topological sort of the graph s.
func (s topoSorter) Sort() []*instance {
var (
states = make(map[*instance]state)
order []*instance
)
for key := range s {
order = s.visit(key, states, order)
}
return order
}
// Cycle returns the first cycle, if any, in the graph.
func (s topoSorter) Cycle() []*instance {
states := make(map[*instance]state)
for key := range s {
if trail := s.cycles(key, nil, states); trail != nil {
return trail
}
}
return nil
}
func (s topoSorter) cycles(key *instance, trail []*instance, states map[*instance]state) []*instance {
switch states[key] {
case todo:
states[key] = visiting
trail = append(trail, key)
for _, child := range s[key] {
if cycle := s.cycles(child, trail, states); cycle != nil {
return cycle
}
}
states[key] = visited
return nil
case visiting:
// Find the previous instance of key in the trail.
for i := range trail {
if trail[i] == key {
trail = trail[i:]
break
}
}
return append(trail, key)
case visited:
return nil
default:
panic("invalid state")
}
}
func (s topoSorter) visit(key *instance, states map[*instance]state, order []*instance) []*instance {
switch states[key] {
case todo:
states[key] = visiting
for _, child := range s[key] {
order = s.visit(child, states, order)
}
states[key] = visited
return append(order, key)
case visiting:
panic("cycle in graph involving node " + key.Impl())
case visited:
return order
default:
panic("invalid state")
}
}