github.com/singularityware/singularity@v3.1.1+incompatible/pkg/util/copy/writer.go (about)

     1  // Copyright (c) 2018, Sylabs Inc. All rights reserved.
     2  // This software is licensed under a 3-clause BSD license. Please consult the
     3  // LICENSE.md file distributed with the sources of this project regarding your
     4  // rights to use or distribute this software.
     5  
     6  package copy
     7  
     8  import (
     9  	"io"
    10  	"sync"
    11  )
    12  
    13  // MultiWriter creates a writer that duplicates its writes to all the provided writers,
    14  // writers can be added / removed dynamically.
    15  type MultiWriter struct {
    16  	mutex   sync.Mutex
    17  	writers []io.Writer
    18  }
    19  
    20  // Write implements the standard Write interface to duplicate data to all writers.
    21  func (mw *MultiWriter) Write(p []byte) (n int, err error) {
    22  	mw.mutex.Lock()
    23  	defer mw.mutex.Unlock()
    24  
    25  	l := len(p)
    26  
    27  	for _, w := range mw.writers {
    28  		n, err = w.Write(p)
    29  		if err != nil {
    30  			return
    31  		}
    32  		if n != l {
    33  			err = io.ErrShortWrite
    34  			return
    35  		}
    36  	}
    37  
    38  	return l, nil
    39  }
    40  
    41  // Add adds a writer.
    42  func (mw *MultiWriter) Add(writer io.Writer) {
    43  	if writer == nil {
    44  		return
    45  	}
    46  	mw.mutex.Lock()
    47  	mw.writers = append(mw.writers, writer)
    48  	mw.mutex.Unlock()
    49  }
    50  
    51  // Del removes a writer.
    52  func (mw *MultiWriter) Del(writer io.Writer) {
    53  	mw.mutex.Lock()
    54  	for i, w := range mw.writers {
    55  		if writer == w {
    56  			mw.writers = append(mw.writers[:i], mw.writers[i+1:]...)
    57  			break
    58  		}
    59  	}
    60  	mw.mutex.Unlock()
    61  }