github.com/looshlee/cilium@v1.6.12/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  	"github.com/cilium/cilium/pkg/lock"
    22  )
    23  
    24  // A Writer is a struct that has a variable-sized `bytes.Buffer` and one
    25  // outWriter(`io.writer`) to stream data
    26  type Writer struct {
    27  	Buffer    *bytes.Buffer
    28  	outWriter io.Writer
    29  	lock      *lock.Mutex
    30  }
    31  
    32  // NewWriter creates and initializes a Writer with a empty Buffer and the given
    33  // outWriter
    34  func NewWriter(outWriter io.Writer) *Writer {
    35  	return &Writer{
    36  		Buffer:    &bytes.Buffer{},
    37  		outWriter: outWriter,
    38  		lock:      &lock.Mutex{},
    39  	}
    40  }
    41  
    42  // Write appends the contents of b to the buffer and outWriter, growing the
    43  // buffer as needed. The return value n is the length of p; err is always nil.
    44  // If the buffer becomes too large, Write will panic with ErrTooLarge.
    45  func (w *Writer) Write(b []byte) (n int, err error) {
    46  	w.lock.Lock()
    47  	defer w.lock.Unlock()
    48  	n, err = w.Buffer.Write(b)
    49  	if err != nil {
    50  		return n, err
    51  	}
    52  	return w.outWriter.Write(b)
    53  }
    54  
    55  // Reset resets the buffer to be empty,
    56  func (w *Writer) Reset() {
    57  	w.lock.Lock()
    58  	defer w.lock.Unlock()
    59  	w.Buffer.Reset()
    60  }
    61  
    62  // Bytes returns a slice based on buffer.Bytes()
    63  func (w *Writer) Bytes() []byte {
    64  	w.lock.Lock()
    65  	defer w.lock.Unlock()
    66  	return w.Buffer.Bytes()
    67  }