2017-05-30 22:36:49 +02:00
|
|
|
package main
|
|
|
|
|
2017-07-01 23:29:22 +02:00
|
|
|
import (
|
2017-08-11 16:18:20 +02:00
|
|
|
"sync/atomic"
|
2017-07-01 23:29:22 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2017-07-08 23:51:26 +02:00
|
|
|
/* We use int32 as atomic bools
|
|
|
|
* (since booleans are not natively supported by sync/atomic)
|
|
|
|
*/
|
|
|
|
const (
|
2017-08-11 16:18:20 +02:00
|
|
|
AtomicFalse = int32(iota)
|
2017-07-08 23:51:26 +02:00
|
|
|
AtomicTrue
|
|
|
|
)
|
|
|
|
|
2017-08-11 16:18:20 +02:00
|
|
|
type AtomicBool struct {
|
|
|
|
flag int32
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *AtomicBool) Get() bool {
|
|
|
|
return atomic.LoadInt32(&a.flag) == AtomicTrue
|
|
|
|
}
|
|
|
|
|
2017-11-17 17:25:45 +01:00
|
|
|
func (a *AtomicBool) Swap(val bool) bool {
|
|
|
|
flag := AtomicFalse
|
|
|
|
if val {
|
|
|
|
flag = AtomicTrue
|
|
|
|
}
|
|
|
|
return atomic.SwapInt32(&a.flag, flag) == AtomicTrue
|
|
|
|
}
|
|
|
|
|
2017-08-11 16:18:20 +02:00
|
|
|
func (a *AtomicBool) Set(val bool) {
|
|
|
|
flag := AtomicFalse
|
|
|
|
if val {
|
|
|
|
flag = AtomicTrue
|
|
|
|
}
|
|
|
|
atomic.StoreInt32(&a.flag, flag)
|
|
|
|
}
|
|
|
|
|
2017-09-24 21:35:25 +02:00
|
|
|
func toInt32(n uint32) int32 {
|
|
|
|
mask := uint32(1 << 31)
|
|
|
|
return int32(-(n & mask) + (n & ^mask))
|
|
|
|
}
|
|
|
|
|
2017-05-30 22:36:49 +02:00
|
|
|
func min(a uint, b uint) uint {
|
|
|
|
if a > b {
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
return a
|
|
|
|
}
|
2017-06-30 14:41:08 +02:00
|
|
|
|
2017-07-10 12:09:19 +02:00
|
|
|
func minUint64(a uint64, b uint64) uint64 {
|
|
|
|
if a > b {
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
2017-07-08 23:51:26 +02:00
|
|
|
func signalSend(c chan struct{}) {
|
2017-06-30 14:41:08 +02:00
|
|
|
select {
|
|
|
|
case c <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2017-07-01 23:29:22 +02:00
|
|
|
|
2017-07-08 23:51:26 +02:00
|
|
|
func signalClear(c chan struct{}) {
|
|
|
|
select {
|
|
|
|
case <-c:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func timerStop(timer *time.Timer) {
|
2017-07-01 23:29:22 +02:00
|
|
|
if !timer.Stop() {
|
|
|
|
select {
|
|
|
|
case <-timer.C:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-07-08 23:51:26 +02:00
|
|
|
func NewStoppedTimer() *time.Timer {
|
2017-07-01 23:29:22 +02:00
|
|
|
timer := time.NewTimer(time.Hour)
|
2017-07-08 23:51:26 +02:00
|
|
|
timerStop(timer)
|
2017-07-01 23:29:22 +02:00
|
|
|
return timer
|
|
|
|
}
|