Skip to content

Instantly share code, notes, and snippets.

@joshuarubin
Last active September 29, 2016 19:59
Show Gist options
  • Save joshuarubin/1a14ae9c11f72bce4f3bd27e7edf9e54 to your computer and use it in GitHub Desktop.
Save joshuarubin/1a14ae9c11f72bce4f3bd27e7edf9e54 to your computer and use it in GitHub Desktop.
hodor7
// Processor implements an io.Reader
type Processor struct {
Src io.Reader
Old, New []byte
ChunkSize int
buf, rbuf bytes.Buffer
}
// Reset the processor
func (m *Processor) Reset(src io.Reader) {
m.Src = src
m.buf.Reset()
}
func (m *Processor) Read(p []byte) (int, error) {
if m.ChunkSize == 0 {
m.ChunkSize = DefaultChunkSize
}
// first flush any buffered data to p
n, err := m.buf.Read(p)
if n == len(p) || (err != nil && err != io.EOF) {
return n, err
}
// m.buf must be empty now
_, err = io.CopyN(&m.buf, m.Src, int64(m.ChunkSize))
if err != nil && err != io.EOF {
return n, err
}
rerr := Replace(m.buf.Bytes(), m.Old, m.New, -1, &m.rbuf)
m.buf.Reset()
if rerr != nil {
return n, rerr
}
copied, rerr := m.rbuf.Read(p[n:])
n += copied
if rerr != nil && rerr != io.EOF {
return n, rerr
}
// copy anything not put in p, back to the buffer
if _, rerr := m.buf.ReadFrom(&m.rbuf); rerr != nil {
return n, rerr
}
return n, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment