-
Notifications
You must be signed in to change notification settings - Fork 0
/
piggyback.go
51 lines (39 loc) · 1.09 KB
/
piggyback.go
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
// Contains functionality for accessing and updating piggyback messages.
package main
import (
"fmt"
"sync"
)
var piggybacks PiggybackMessages
var piggybacksLock = sync.RWMutex{}
func PrintPiggybackMessages() {
piggybacksLock.RLock()
defer piggybacksLock.RUnlock()
for _, p := range piggybacks {
fmt.Println(p)
}
}
func AddPiggybackMessage(message Message) {
piggybacksLock.Lock()
defer piggybacksLock.Unlock()
piggybacks = append(piggybacks, PiggybackMessage{message, PIGGYBACK_TTL})
}
// Returns messages from Piggyback that aren't expired.
func GetUnexpiredPiggybackMessages() Messages {
var messages Messages
piggybacksLock.Lock()
defer piggybacksLock.Unlock()
addedPiggybacks := 0
for index := 0; (index < len(piggybacks)) && (addedPiggybacks < 5); index++ { // Piggyback only 4 messages at max
if piggybacks[index].ttl > 0 {
messages = append(messages, piggybacks[index].message)
piggybacks[index].ttl--
addedPiggybacks += 1
}
if piggybacks[index].ttl <= 0 {
piggybacks = append(piggybacks[:index], piggybacks[index+1:]...)
index--
}
}
return messages
}