codecutil: made zeroTicks global

This commit is contained in:
Trek H 2019-07-15 17:55:42 +09:30
parent eb4a325981
commit 8518d931c6
1 changed files with 20 additions and 16 deletions

View File

@ -40,8 +40,23 @@ func NewByteLexer(bufSize *int) *ByteLexer {
return &ByteLexer{bufSize: bufSize} return &ByteLexer{bufSize: bufSize}
} }
// Lex reads *l.bufSize bytes from src and writes them to dst every t seconds. // zeroTicks can be used to create an instant ticker.
func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, t time.Duration) error { var zeroTicks chan time.Time
func init() {
zeroTicks = make(chan time.Time)
close(zeroTicks)
}
func newTicker(d time.Duration) *time.Ticker {
if d == 0 {
return &time.Ticker{C: zeroTicks}
}
return time.NewTicker(d)
}
// Lex reads *l.bufSize bytes from src and writes them to dst every d seconds.
func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, d time.Duration) error {
if l.bufSize == nil { if l.bufSize == nil {
return fmt.Errorf("buffer size has not been set") return fmt.Errorf("buffer size has not been set")
} }
@ -49,22 +64,11 @@ func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, t time.Duration) error {
if bufSize <= 0 { if bufSize <= 0 {
return fmt.Errorf("invalid buffer size: %v", bufSize) return fmt.Errorf("invalid buffer size: %v", bufSize)
} }
if t < 0 { if d < 0 {
return fmt.Errorf("invalid delay: %v", t) return fmt.Errorf("invalid delay: %v", d)
} }
// Set up delay, make loop instant if t is 0. ticker := newTicker(d)
var ticker *time.Ticker
var zeroTicks chan time.Time
if t > 0 {
ticker = time.NewTicker(t)
} else {
zeroTicks = make(chan time.Time)
close(zeroTicks)
ticker = &time.Ticker{C: zeroTicks}
}
defer ticker.Stop()
buf := make([]byte, bufSize) buf := make([]byte, bufSize)
for { for {
<-ticker.C <-ticker.C