Debian Codegraph @

store.go

raw symbols SCIP
1 package graph
2
3 import (
4 "fmt"
5 "sync"
6 )
7
8 // Store represents a storage for vertices and edges. The graph library provides an in-memory store
9 // by default and accepts any Store implementation to work with - for example, an SQL store.
10 //
11 // When implementing your own Store, make sure the individual methods and their behavior adhere to
12 // this documentation. Otherwise, the graphs aren't guaranteed to behave as expected.
13 type Store[K comparable, T any] interface {
14 // AddVertex should add the given vertex with the given hash value and vertex properties to the
15 // graph. If the vertex already exists, it is up to you whether ErrVertexAlreadyExists or no
16 // error should be returned.
17 AddVertex(hash K, value T, properties VertexProperties) error
18
19 // Vertex should return the vertex and vertex properties with the given hash value. If the
20 // vertex doesn't exist, ErrVertexNotFound should be returned.
21 Vertex(hash K) (T, VertexProperties, error)
22
23 // RemoveVertex should remove the vertex with the given hash value. If the vertex doesn't
24 // exist, ErrVertexNotFound should be returned. If the vertex has edges to other vertices,
25 // ErrVertexHasEdges should be returned.
26 RemoveVertex(hash K) error
27
28 // ListVertices should return all vertices in the graph in a slice.
29 ListVertices() ([]K, error)
30
31 // VertexCount should return the number of vertices in the graph. This should be equal to the
32 // length of the slice returned by ListVertices.
33 VertexCount() (int, error)
34
35 // AddEdge should add an edge between the vertices with the given source and target hashes.
36 //
37 // If either vertex doesn't exit, ErrVertexNotFound should be returned for the respective
38 // vertex. If the edge already exists, ErrEdgeAlreadyExists should be returned.
39 AddEdge(sourceHash, targetHash K, edge Edge[K]) error
40
41 // UpdateEdge should update the edge between the given vertices with the data of the given
42 // Edge instance. If the edge doesn't exist, ErrEdgeNotFound should be returned.
43 UpdateEdge(sourceHash, targetHash K, edge Edge[K]) error
44
45 // RemoveEdge should remove the edge between the vertices with the given source and target
46 // hashes.
47 //
48 // If either vertex doesn't exist, it is up to you whether ErrVertexNotFound or no error should
49 // be returned. If the edge doesn't exist, it is up to you whether ErrEdgeNotFound or no error
50 // should be returned.
51 RemoveEdge(sourceHash, targetHash K) error
52
53 // Edge should return the edge joining the vertices with the given hash values. It should
54 // exclusively look for an edge between the source and the target vertex, not vice versa. The
55 // graph implementation does this for undirected graphs itself.
56 //
57 // Note that unlike Graph.Edge, this function is supposed to return an Edge[K], i.e. an edge
58 // that only contains the vertex hashes instead of the vertices themselves.
59 //
60 // If the edge doesn't exist, ErrEdgeNotFound should be returned.
61 Edge(sourceHash, targetHash K) (Edge[K], error)
62
63 // ListEdges should return all edges in the graph in a slice.
64 ListEdges() ([]Edge[K], error)
65 }
66
67 type memoryStore[K comparable, T any] struct {
68 lock sync.RWMutex
69 vertices map[K]T
70 vertexProperties map[K]VertexProperties
71
72 // outEdges and inEdges store all outgoing and ingoing edges for all vertices. For O(1) access,
73 // these edges themselves are stored in maps whose keys are the hashes of the target vertices.
74 outEdges map[K]map[K]Edge[K] // source -> target
75 inEdges map[K]map[K]Edge[K] // target -> source
76 }
77
78 func newMemoryStore[K comparable, T any]() Store[K, T] {
79 return &memoryStore[K, T]{
80 vertices: make(map[K]T),
81 vertexProperties: make(map[K]VertexProperties),
82 outEdges: make(map[K]map[K]Edge[K]),
83 inEdges: make(map[K]map[K]Edge[K]),
84 }
85 }
86
87 func (s *memoryStore[K, T]) AddVertex(k K, t T, p VertexProperties) error {
88 s.lock.Lock()
89 defer s.lock.Unlock()
90
91 if _, ok := s.vertices[k]; ok {
92 return ErrVertexAlreadyExists
93 }
94
95 s.vertices[k] = t
96 s.vertexProperties[k] = p
97
98 return nil
99 }
100
101 func (s *memoryStore[K, T]) ListVertices() ([]K, error) {
102 s.lock.RLock()
103 defer s.lock.RUnlock()
104
105 hashes := make([]K, 0, len(s.vertices))
106 for k := range s.vertices {
107 hashes = append(hashes, k)
108 }
109
110 return hashes, nil
111 }
112
113 func (s *memoryStore[K, T]) VertexCount() (int, error) {
114 s.lock.RLock()
115 defer s.lock.RUnlock()
116
117 return len(s.vertices), nil
118 }
119
120 func (s *memoryStore[K, T]) Vertex(k K) (T, VertexProperties, error) {
121 s.lock.RLock()
122 defer s.lock.RUnlock()
123
124 v, ok := s.vertices[k]
125 if !ok {
126 return v, VertexProperties{}, ErrVertexNotFound
127 }
128
129 p := s.vertexProperties[k]
130
131 return v, p, nil
132 }
133
134 func (s *memoryStore[K, T]) RemoveVertex(k K) error {
135 s.lock.RLock()
136 defer s.lock.RUnlock()
137
138 if _, ok := s.vertices[k]; !ok {
139 return ErrVertexNotFound
140 }
141
142 if edges, ok := s.inEdges[k]; ok {
143 if len(edges) > 0 {
144 return ErrVertexHasEdges
145 }
146 delete(s.inEdges, k)
147 }
148
149 if edges, ok := s.outEdges[k]; ok {
150 if len(edges) > 0 {
151 return ErrVertexHasEdges
152 }
153 delete(s.outEdges, k)
154 }
155
156 delete(s.vertices, k)
157 delete(s.vertexProperties, k)
158
159 return nil
160 }
161
162 func (s *memoryStore[K, T]) AddEdge(sourceHash, targetHash K, edge Edge[K]) error {
163 s.lock.Lock()
164 defer s.lock.Unlock()
165
166 if _, ok := s.outEdges[sourceHash]; !ok {
167 s.outEdges[sourceHash] = make(map[K]Edge[K])
168 }
169
170 s.outEdges[sourceHash][targetHash] = edge
171
172 if _, ok := s.inEdges[targetHash]; !ok {
173 s.inEdges[targetHash] = make(map[K]Edge[K])
174 }
175
176 s.inEdges[targetHash][sourceHash] = edge
177
178 return nil
179 }
180
181 func (s *memoryStore[K, T]) UpdateEdge(sourceHash, targetHash K, edge Edge[K]) error {
182 if _, err := s.Edge(sourceHash, targetHash); err != nil {
183 return err
184 }
185
186 s.lock.Lock()
187 defer s.lock.Unlock()
188
189 s.outEdges[sourceHash][targetHash] = edge
190 s.inEdges[targetHash][sourceHash] = edge
191
192 return nil
193 }
194
195 func (s *memoryStore[K, T]) RemoveEdge(sourceHash, targetHash K) error {
196 s.lock.Lock()
197 defer s.lock.Unlock()
198
199 delete(s.inEdges[targetHash], sourceHash)
200 delete(s.outEdges[sourceHash], targetHash)
201 return nil
202 }
203
204 func (s *memoryStore[K, T]) Edge(sourceHash, targetHash K) (Edge[K], error) {
205 s.lock.RLock()
206 defer s.lock.RUnlock()
207
208 sourceEdges, ok := s.outEdges[sourceHash]
209 if !ok {
210 return Edge[K]{}, ErrEdgeNotFound
211 }
212
213 edge, ok := sourceEdges[targetHash]
214 if !ok {
215 return Edge[K]{}, ErrEdgeNotFound
216 }
217
218 return edge, nil
219 }
220
221 func (s *memoryStore[K, T]) ListEdges() ([]Edge[K], error) {
222 s.lock.RLock()
223 defer s.lock.RUnlock()
224
225 res := make([]Edge[K], 0)
226 for _, edges := range s.outEdges {
227 for _, edge := range edges {
228 res = append(res, edge)
229 }
230 }
231 return res, nil
232 }
233
234 // CreatesCycle is a fastpath version of [CreatesCycle] that avoids calling
235 // [PredecessorMap], which generates large amounts of garbage to collect.
236 //
237 // Because CreatesCycle doesn't need to modify the PredecessorMap, we can use
238 // inEdges instead to compute the same thing without creating any copies.
239 func (s *memoryStore[K, T]) CreatesCycle(source, target K) (bool, error) {
240 if _, _, err := s.Vertex(source); err != nil {
241 return false, fmt.Errorf("could not get vertex with hash %v: %w", source, err)
242 }
243
244 if _, _, err := s.Vertex(target); err != nil {
245 return false, fmt.Errorf("could not get vertex with hash %v: %w", target, err)
246 }
247
248 if source == target {
249 return true, nil
250 }
251
252 stack := make([]K, 0)
253 visited := make(map[K]struct{})
254
255 stack = append(stack, source)
256 for len(stack) > 0 {
257 currentHash := stack[len(stack)-1]
258 stack = stack[:len(stack)-1]
259
260 if _, ok := visited[currentHash]; !ok {
261 // If the adjacent vertex also is the target vertex, the target is a
262 // parent of the source vertex. An edge would introduce a cycle.
263 if currentHash == target {
264 return true, nil
265 }
266
267 visited[currentHash] = struct{}{}
268
269 for adjacency := range s.inEdges[currentHash] {
270 stack = append(stack, adjacency)
271 }
272 }
273 }
274
275 return false, nil
276 }