github.com/blend/go-sdk@v1.20240719.1/logger/lines_writer.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package logger
     9  
    10  import (
    11  	"bytes"
    12  	"io"
    13  
    14  	"github.com/blend/go-sdk/ex"
    15  )
    16  
    17  // NOTE: Ensure that
    18  //   - `LinesWriter` satisfies `io.Writer`.
    19  var (
    20  	_ io.Writer = (*LinesWriter)(nil)
    21  )
    22  
    23  // LinesWriter is a writer that writes one line at a time, i.e. if `Write()` is called
    24  // with multiple lines, `w.Write()` will be called for each line.
    25  type LinesWriter struct {
    26  	w io.Writer
    27  }
    28  
    29  // NewLinesWriter returns a new line writer.
    30  func NewLinesWriter(w io.Writer) *LinesWriter {
    31  	return &LinesWriter{
    32  		w: w,
    33  	}
    34  }
    35  
    36  // Write implements io.Writer.
    37  func (lw *LinesWriter) Write(p []byte) (int, error) {
    38  	n := 0
    39  	for {
    40  		eol := bytes.Index(p, []byte("\n"))
    41  		if eol == -1 {
    42  			break
    43  		}
    44  		lineN, err := lw.w.Write(p[:eol])
    45  		n += lineN + 1
    46  		if err != nil {
    47  			return n, ex.New(err)
    48  		}
    49  		p = p[eol+1:]
    50  	}
    51  	lineN, err := lw.w.Write(p)
    52  	return n + lineN, ex.New(err)
    53  }