1// Package util contains miscellaneous utilities used by yggdrasil.
2// In particular, this includes a crypto worker pool, Cancellation machinery, and a sync.Pool used to reuse []byte.
3package util
4
5// These are misc. utility functions that didn't really fit anywhere else
6
7import (
8	"time"
9)
10
11// TimerStop stops a timer and makes sure the channel is drained, returns true if the timer was stopped before firing.
12func TimerStop(t *time.Timer) bool {
13	stopped := t.Stop()
14	select {
15	case <-t.C:
16	default:
17	}
18	return stopped
19}
20
21// FuncTimeout runs the provided function in a separate goroutine, and returns true if the function finishes executing before the timeout passes, or false if the timeout passes.
22// It includes no mechanism to stop the function if the timeout fires, so the user is expected to do so on their own (such as with a Cancellation or a context).
23func FuncTimeout(timeout time.Duration, f func()) bool {
24	success := make(chan struct{})
25	go func() {
26		defer close(success)
27		f()
28	}()
29	timer := time.NewTimer(timeout)
30	defer TimerStop(timer)
31	select {
32	case <-success:
33		return true
34	case <-timer.C:
35		return false
36	}
37}
38