added communities pool

This commit is contained in:
Annika Hannig 2022-11-16 10:51:49 +01:00
parent a8c3c11fd2
commit b10634d666
2 changed files with 89 additions and 0 deletions

45
pkg/pools/communities.go Normal file
View File

@ -0,0 +1,45 @@
package pools
import (
"reflect"
"sync"
"github.com/alice-lg/alice-lg/pkg/api"
)
// Communities is a pool for deduplicating a list of BGP communities
// (Large and default. The ext communities representation right now
// makes problems and need to be fixed. TODO.)
type Communities struct {
communities *IntList
root *Node
sync.Mutex
}
// NewCommunities creates a new pool for lists
// of BGP communities.
func NewCommunities() *Communities {
return &Communities{
communities: NewIntList(),
root: &Node{
ptr: []api.Community{},
},
}
}
// Acquire a list of bgp communities
func (p *Communities) Acquire(communities []api.Community) []api.Community {
ids := make([]int, len(communities))
for i, comm := range communities {
commPtr := p.communities.Acquire(comm)
addr := reflect.ValueOf(commPtr).UnsafePointer()
ids[i] = int(uintptr(addr))
}
p.Lock()
defer p.Unlock()
if len(ids) == 0 {
return p.root.ptr.([]api.Community)
}
return p.root.traverse(communities, ids).([]api.Community)
}

View File

@ -0,0 +1,44 @@
package pools
import (
"fmt"
"testing"
"github.com/alice-lg/alice-lg/pkg/api"
)
func TestAcquireCommunities(t *testing.T) {
c1 := []api.Community{
{2342, 5, 1},
{2342, 5, 2},
{2342, 51, 1},
}
c2 := []api.Community{
{2342, 5, 1},
{2342, 5, 2},
{2342, 51, 1},
}
c3 := []api.Community{
{2341, 6, 1},
{2341, 6, 2},
{2341, 1, 1},
}
p := NewCommunities()
pc1 := p.Acquire(c1)
pc2 := p.Acquire(c2)
pc3 := p.Acquire(c3)
if fmt.Sprintf("%p", c1) == fmt.Sprintf("%p", c2) {
t.Error("expected c1 !== c2")
}
if fmt.Sprintf("%p", pc1) != fmt.Sprintf("%p", pc2) {
t.Error("expected pc1 == pc2")
}
fmt.Printf("c1: %p, c2: %p, c3: %p\n", c1, c2, c3)
fmt.Printf("pc1: %p, pc2: %p, pc3: %p\n", pc1, pc2, pc3)
}