From 8518d931c6a10876061d28e280a3ce14ad08f282 Mon Sep 17 00:00:00 2001 From: Trek H Date: Mon, 15 Jul 2019 17:55:42 +0930 Subject: [PATCH] codecutil: made zeroTicks global --- codec/codecutil/lex.go | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/codec/codecutil/lex.go b/codec/codecutil/lex.go index 98953a93..158839dd 100644 --- a/codec/codecutil/lex.go +++ b/codec/codecutil/lex.go @@ -40,8 +40,23 @@ func NewByteLexer(bufSize *int) *ByteLexer { return &ByteLexer{bufSize: bufSize} } -// Lex reads *l.bufSize bytes from src and writes them to dst every t seconds. -func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, t time.Duration) error { +// zeroTicks can be used to create an instant ticker. +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 { 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 { return fmt.Errorf("invalid buffer size: %v", bufSize) } - if t < 0 { - return fmt.Errorf("invalid delay: %v", t) + if d < 0 { + return fmt.Errorf("invalid delay: %v", d) } - // Set up delay, make loop instant if t is 0. - 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() - + ticker := newTicker(d) buf := make([]byte, bufSize) for { <-ticker.C