From 714c83b2736d7e308bc33c49057952490eb98be2 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 20 Oct 2024 23:07:42 +0200 Subject: Adding upstream version 1.21.4. Signed-off-by: Daniel Baumann --- pkg/common/line_writer.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 pkg/common/line_writer.go (limited to 'pkg/common/line_writer.go') diff --git a/pkg/common/line_writer.go b/pkg/common/line_writer.go new file mode 100644 index 0000000..2035199 --- /dev/null +++ b/pkg/common/line_writer.go @@ -0,0 +1,50 @@ +package common + +import ( + "bytes" + "io" +) + +// LineHandler is a callback function for handling a line +type LineHandler func(line string) bool + +type lineWriter struct { + buffer bytes.Buffer + handlers []LineHandler +} + +// NewLineWriter creates a new instance of a line writer +func NewLineWriter(handlers ...LineHandler) io.Writer { + w := new(lineWriter) + w.handlers = handlers + return w +} + +func (lw *lineWriter) Write(p []byte) (n int, err error) { + pBuf := bytes.NewBuffer(p) + written := 0 + for { + line, err := pBuf.ReadString('\n') + w, _ := lw.buffer.WriteString(line) + written += w + if err == nil { + lw.handleLine(lw.buffer.String()) + lw.buffer.Reset() + } else if err == io.EOF { + break + } else { + return written, err + } + } + + return written, nil +} + +func (lw *lineWriter) handleLine(line string) { + for _, h := range lw.handlers { + ok := h(line) + if !ok { + break + } + } +} -- cgit v1.2.3