swarm/pss: minor refactoring

This commit is contained in:
Vlad 2019-04-16 14:39:45 +02:00
parent c5e2a6dc7a
commit 0b23499afb

View file

@ -63,15 +63,15 @@ func (td *testData) pushNotification(val handlerNotification) {
td.mu.Unlock() td.mu.Unlock()
} }
func (td *testData) popNotification() (first handlerNotification, ok bool) { func (td *testData) popNotification() (first handlerNotification, exist bool) {
td.mu.Lock() td.mu.Lock()
if len(td.notifications) > 0 { if len(td.notifications) > 0 {
ok = true exist = true
first = td.notifications[0] first = td.notifications[0]
td.notifications = td.notifications[1:] td.notifications = td.notifications[1:]
} }
td.mu.Unlock() td.mu.Unlock()
return first, ok return first, exist
} }
func (td *testData) getMsgCount() int { func (td *testData) getMsgCount() int {
@ -272,33 +272,34 @@ func (td *testData) sendAllMsgs() error {
return nil return nil
} }
// testRoutine is the main test function, called by Simulation.Run() func isMoreTimeLeft(ctx context.Context) bool {
func testRoutine(td *testData, ctx context.Context) error {
if err := td.sendAllMsgs(); err != nil {
return err
}
isMoreTimeLeft := func() bool {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return false return false
default: default:
return true return true
} }
} }
// testRoutine is the main test function, called by Simulation.Run()
func testRoutine(td *testData, ctx context.Context) error {
hasMoreRound := func(err error, hadMessage bool) bool { hasMoreRound := func(err error, hadMessage bool) bool {
return err == nil && (hadMessage || isMoreTimeLeft()) return err == nil && (hadMessage || isMoreTimeLeft(ctx))
}
if err := td.sendAllMsgs(); err != nil {
return err
} }
var err error var err error
received := 0 received := 0
hadMessage := false hadMessage := false
for oneMoreRound := true; oneMoreRound; oneMoreRound = hasMoreRound(err, hadMessage) { for oneMoreRound := true; oneMoreRound; oneMoreRound = hasMoreRound(err, hadMessage) {
message, hadMessage := td.popNotification() message, hadMessage := td.popNotification()
if !isMoreTimeLeft() { if !isMoreTimeLeft(ctx) {
// Stop handlers from sending more messages. // Stop handlers from sending more messages.
// Note: only best effort, race is possible. // Note: only best effort, race is possible.
td.setDone() td.setDone()
@ -314,8 +315,6 @@ func testRoutine(td *testData, ctx context.Context) error {
} else { } else {
time.Sleep(32 * time.Millisecond) time.Sleep(32 * time.Millisecond)
} }
oneMoreRound = err == nil && (hadMessage || isMoreTimeLeft())
} }
if err != nil { if err != nil {
@ -326,7 +325,6 @@ func testRoutine(td *testData, ctx context.Context) error {
return ctx.Err() return ctx.Err()
} }
return nil return nil
} }
func (td *testData) isAllowedMessage(n handlerNotification) bool { func (td *testData) isAllowedMessage(n handlerNotification) bool {