-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring.go
More file actions
99 lines (77 loc) · 1.68 KB
/
Copy pathring.go
File metadata and controls
99 lines (77 loc) · 1.68 KB
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
package storage
import (
"sync"
"github.com/jnaraujo/tec502-inter-bank/bank/internal/interbank"
)
type ringData struct {
Id interbank.BankId
Addr string
}
// implementação de um token ring para
// comunicação entre os bancos
type ringStorage struct {
mu sync.RWMutex
ring []ringData
}
var Ring = &ringStorage{}
// Adiciona um banco ao anel de comunicação
func (r *ringStorage) Add(bankId interbank.BankId, addr string) {
r.mu.Lock()
defer r.mu.Unlock()
r.ring = append(r.ring, ringData{Id: bankId, Addr: addr})
}
func (r *ringStorage) Find(bankId interbank.BankId) *ringData {
r.mu.RLock()
defer r.mu.RUnlock()
for _, bank := range r.ring {
if bank.Id == bankId {
return &bank
}
}
return nil
}
// Retorna o próximo banco no anel de comunicação
func (r *ringStorage) Next(bankId interbank.BankId) *ringData {
r.mu.RLock()
defer r.mu.RUnlock()
for i, bank := range r.ring {
if bank.Id == bankId {
if i+1 == len(r.ring) {
return &r.ring[0]
}
return &r.ring[i+1]
}
}
return nil
}
// Retorna o banco anterior no anel de comunicação
func (r *ringStorage) Before(bankId interbank.BankId) *ringData {
r.mu.RLock()
defer r.mu.RUnlock()
for i, bank := range r.ring {
if bank.Id == bankId {
if i == 0 {
return &r.ring[len(r.ring)-1]
}
return &r.ring[i-1]
}
}
return nil
}
// Retorna o anel de comunicação
func (r *ringStorage) List() []ringData {
r.mu.RLock()
defer r.mu.RUnlock()
return r.ring
}
func (r *ringStorage) FindBankWithLowestId() *ringData {
r.mu.RLock()
defer r.mu.RUnlock()
lowest := r.ring[0]
for _, bank := range r.ring {
if int(bank.Id) < int(lowest.Id) {
lowest = bank
}
}
return &lowest
}