Skip to content

Commit c6e442f

Browse files
committed
[FAB-7435] Graph struct for service discovery
This change set adds a generic graph that is going to be used for associating principals with peer identities that satisfy principals. Change-Id: I2043a332b92683d8f6ae7298e1a4b6a8158c9d0f Signed-off-by: yacovm <yacovm@il.ibm.com>
1 parent 963ee5b commit c6e442f

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

common/graph/graph.go

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Copyright IBM Corp. All Rights Reserved.
3+
4+
SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
package graph
8+
9+
// Vertex defines a vertex of a graph
10+
type Vertex struct {
11+
Id string
12+
Data interface{}
13+
neighbors map[string]*Vertex
14+
}
15+
16+
// NewVertex creates a new vertex with given id and data
17+
func NewVertex(id string, data interface{}) *Vertex {
18+
return &Vertex{
19+
Id: id,
20+
Data: data,
21+
neighbors: make(map[string]*Vertex),
22+
}
23+
}
24+
25+
// NeighborById returns a neighbor vertex with the given id,
26+
// or nil if no vertex with such an id is a neighbor
27+
func (v *Vertex) NeighborById(id string) *Vertex {
28+
return v.neighbors[id]
29+
}
30+
31+
// Neighbors returns the neighbors of the vertex
32+
func (v *Vertex) Neighbors() []*Vertex {
33+
var res []*Vertex
34+
for _, u := range v.neighbors {
35+
res = append(res, u)
36+
}
37+
return res
38+
}
39+
40+
// AddNeighbor adds the given vertex as a neighbor
41+
// of the vertex
42+
func (v *Vertex) AddNeighbor(u *Vertex) {
43+
v.neighbors[u.Id] = u
44+
u.neighbors[v.Id] = v
45+
}

common/graph/graph_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/*
2+
Copyright IBM Corp. All Rights Reserved.
3+
4+
SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
package graph
8+
9+
import (
10+
"testing"
11+
12+
"github.com/stretchr/testify/assert"
13+
)
14+
15+
func TestVertex(t *testing.T) {
16+
v := NewVertex("1", "1")
17+
assert.Equal(t, "1", v.Data)
18+
assert.Equal(t, "1", v.Id)
19+
u := NewVertex("2", "2")
20+
v.AddNeighbor(u)
21+
assert.Contains(t, u.Neighbors(), v)
22+
assert.Contains(t, v.Neighbors(), u)
23+
assert.Equal(t, u, v.NeighborById("2"))
24+
assert.Nil(t, v.NeighborById("3"))
25+
}

0 commit comments

Comments
 (0)