Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#ifndef GFX_DIRECTEDGRAPH_H
8
#define GFX_DIRECTEDGRAPH_H
9
10
#include "gfxTypes.h"
11
#include "nsTArray.h"
12
13
namespace mozilla {
14
namespace layers {
15
16
template <typename T>
17
class DirectedGraph {
18
public:
19
class Edge {
20
public:
21
Edge(T aFrom, T aTo) : mFrom(aFrom), mTo(aTo) {}
22
23
bool operator==(const Edge& aOther) const {
24
return mFrom == aOther.mFrom && mTo == aOther.mTo;
25
}
26
27
T mFrom;
28
T mTo;
29
};
30
31
class RemoveEdgesToComparator {
32
public:
33
bool Equals(const Edge& a, T const& b) const { return a.mTo == b; }
34
};
35
36
/**
37
* Add a new edge to the graph.
38
*/
39
void AddEdge(Edge aEdge) {
40
NS_ASSERTION(!mEdges.Contains(aEdge), "Adding a duplicate edge!");
41
mEdges.AppendElement(aEdge);
42
}
43
44
void AddEdge(T aFrom, T aTo) { AddEdge(Edge(aFrom, aTo)); }
45
46
/**
47
* Get the list of edges.
48
*/
49
const nsTArray<Edge>& GetEdgeList() const { return mEdges; }
50
51
/**
52
* Remove the given edge from the graph.
53
*/
54
void RemoveEdge(Edge aEdge) { mEdges.RemoveElement(aEdge); }
55
56
/**
57
* Remove all edges going into aNode.
58
*/
59
void RemoveEdgesTo(T aNode) {
60
RemoveEdgesToComparator c;
61
while (mEdges.RemoveElement(aNode, c)) {
62
}
63
}
64
65
/**
66
* Get the number of edges going into aNode.
67
*/
68
unsigned int NumEdgesTo(T aNode) {
69
unsigned int count = 0;
70
for (unsigned int i = 0; i < mEdges.Length(); i++) {
71
if (mEdges.ElementAt(i).mTo == aNode) {
72
count++;
73
}
74
}
75
return count;
76
}
77
78
/**
79
* Get the list of all edges going from aNode
80
*/
81
void GetEdgesFrom(T aNode, nsTArray<Edge>& aResult) {
82
for (unsigned int i = 0; i < mEdges.Length(); i++) {
83
if (mEdges.ElementAt(i).mFrom == aNode) {
84
aResult.AppendElement(mEdges.ElementAt(i));
85
}
86
}
87
}
88
89
/**
90
* Get the total number of edges.
91
*/
92
unsigned int GetEdgeCount() { return mEdges.Length(); }
93
94
private:
95
nsTArray<Edge> mEdges;
96
};
97
98
} // namespace layers
99
} // namespace mozilla
100
101
#endif // GFX_DIRECTEDGRAPH_H