github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/test/ginkgo-ext/writer.go (about)

     1  // Copyright 2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ginkgoext
    16  
    17  import (
    18  	"bytes"
    19  	"io"
    20  )
    21  
    22  // A Writer is a struct that has a variable-sized `bytes.Buffer` and one
    23  // outWriter(`io.writer`) to stream data
    24  type Writer struct {
    25  	Buffer    *bytes.Buffer
    26  	outWriter io.Writer
    27  }
    28  
    29  // NewWriter creates and initializes a Writer with a empty Buffer and the given
    30  // outWriter
    31  func NewWriter(outWriter io.Writer) *Writer {
    32  	return &Writer{
    33  		Buffer:    &bytes.Buffer{},
    34  		outWriter: outWriter,
    35  	}
    36  }
    37  
    38  // Write appends the contents of b to the buffer and outWriter, growing the
    39  // buffer as needed. The return value n is the length of p; err is always nil.
    40  // If the buffer becomes too large, Write will panic with ErrTooLarge.
    41  func (w *Writer) Write(b []byte) (n int, err error) {
    42  	n, err = w.Buffer.Write(b)
    43  	if err != nil {
    44  		return n, err
    45  	}
    46  	return w.outWriter.Write(b)
    47  }
    48  
    49  // Reset resets the buffer to be empty,
    50  func (w *Writer) Reset() {
    51  	w.Buffer.Reset()
    52  }
    53  
    54  // Bytes returns a slice based on buffer.Bytes()
    55  func (w *Writer) Bytes() []byte {
    56  	return w.Buffer.Bytes()
    57  }