diff --git a/codec/codecutil/lex.go b/codec/codecutil/lex.go index 3414ff45..3e1d862d 100644 --- a/codec/codecutil/lex.go +++ b/codec/codecutil/lex.go @@ -53,16 +53,19 @@ func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, t time.Duration) error { return fmt.Errorf("invalid delay: %v", t) } var ticker *time.Ticker + var zeroTicks chan time.Time if t > 0 { ticker = time.NewTicker(t) - defer ticker.Stop() + } else { + zeroTicks = make(chan time.Time) + close(zeroTicks) + ticker = &time.Ticker{C: zeroTicks} } + defer ticker.Stop() buf := make([]byte, bufSize) for { - if t != 0 { - <-ticker.C - } + <-ticker.C off, err := src.Read(buf) if err != nil { return err @@ -73,3 +76,28 @@ func (l *ByteLexer) Lex(dst io.Writer, src io.Reader, t time.Duration) error { } } } + +func main() { + for _, delay := range []time.Duration{0, 10 * time.Millisecond} { + t := newTicker(delay) + for i := 0; i < 10; i++ { + <-t.C + fmt.Println(time.Now(), i) + } + fmt.Println() + } +} + +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) +}