github.com/iDigitalFlame/xmt@v0.5.4/c2/c_compat15.go (about) 1 //go:build !go1.15 2 // +build !go1.15 3 4 // Copyright (C) 2020 - 2023 iDigitalFlame 5 // 6 // This program is free software: you can redistribute it and/or modify 7 // it under the terms of the GNU General Public License as published by 8 // the Free Software Foundation, either version 3 of the License, or 9 // any later version. 10 // 11 // This program is distributed in the hope that it will be useful, 12 // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 // GNU General Public License for more details. 15 // 16 // You should have received a copy of the GNU General Public License 17 // along with this program. If not, see <https://www.gnu.org/licenses/>. 18 // 19 20 package c2 21 22 import "time" 23 24 type sleeper struct { 25 C chan time.Time 26 t *time.Timer 27 p time.Duration 28 w chan struct{} 29 } 30 31 func (s *sleeper) Stop() { 32 close(s.w) 33 } 34 func (s *sleeper) sleep() { 35 inner: 36 for { 37 select { 38 case <-s.w: 39 break inner 40 case t := <-s.t.C: 41 select { 42 case s.C <- t: 43 default: 44 } 45 s.t.Stop() 46 s.t.Reset(s.p) 47 } 48 } 49 s.t.Stop() 50 close(s.C) 51 } 52 func (s *sleeper) Reset(d time.Duration) { 53 for s.t.Stop(); len(s.t.C) > 0; { 54 <-s.t.C 55 } 56 s.p = d 57 s.t.Reset(d) 58 } 59 func newSleeper(d time.Duration) *sleeper { 60 s := &sleeper{C: make(chan time.Time, 1), t: time.NewTimer(d), p: d, w: make(chan struct{})} 61 go s.sleep() 62 return s 63 }