codecutil: updated logic for 0 delay lexing

This commit is contained in:
Trek H 2019-07-15 15:17:16 +09:30
parent be389fca6e
commit 72d56e31ee
1 changed files with 32 additions and 4 deletions

View File

@ -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) return fmt.Errorf("invalid delay: %v", t)
} }
var ticker *time.Ticker var ticker *time.Ticker
var zeroTicks chan time.Time
if t > 0 { if t > 0 {
ticker = time.NewTicker(t) 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) buf := make([]byte, bufSize)
for { for {
if t != 0 {
<-ticker.C <-ticker.C
}
off, err := src.Read(buf) off, err := src.Read(buf)
if err != nil { if err != nil {
return err 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)
}