av/codec/codecutil/lex.go

81 lines
1.9 KiB
Go
Raw Normal View History

/*
NAME
lex.go
AUTHOR
Trek Hopton <trek@ausocean.org>
LICENSE
This file is Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License in gpl.txt.
If not, see [GNU licenses](http://www.gnu.org/licenses).
*/
package codecutil
import (
"fmt"
"io"
"time"
)
// ByteLexer is used to lex bytes using a buffer size which is configured upon construction.
type ByteLexer struct {
bufSize *int
}
// NewByteLexer returns a pointer to a ByteLexer with the given buffer size.
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 {
if l.bufSize == nil {
return fmt.Errorf("buffer size has not been set")
}
bufSize := *l.bufSize
if bufSize <= 0 {
return fmt.Errorf("invalid buffer size: %v", bufSize)
}
if t < 0 {
return fmt.Errorf("invalid delay: %v", t)
}
2019-07-15 09:02:42 +03:00
// Set up delay, make loop instant if t is 0.
2019-07-11 08:24:06 +03:00
var ticker *time.Ticker
var zeroTicks chan time.Time
if t > 0 {
2019-07-11 08:24:06 +03:00
ticker = time.NewTicker(t)
} else {
zeroTicks = make(chan time.Time)
close(zeroTicks)
ticker = &time.Ticker{C: zeroTicks}
}
defer ticker.Stop()
buf := make([]byte, bufSize)
for {
<-ticker.C
off, err := src.Read(buf)
if err != nil {
return err
}
_, err = dst.Write(buf[:off])
if err != nil {
return err
}
}
}