github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/thirdparty/eventlog/writer.go (about)

     1  package eventlog
     2  
     3  import (
     4  	"io"
     5  	"sync"
     6  )
     7  
     8  type MirrorWriter struct {
     9  	writers []io.Writer
    10  	lk      sync.Mutex
    11  }
    12  
    13  func (mw *MirrorWriter) Write(b []byte) (int, error) {
    14  	mw.lk.Lock()
    15  	// write to all writers, and nil out the broken ones.
    16  	for i, w := range mw.writers {
    17  		_, err := w.Write(b)
    18  		if err != nil {
    19  			mw.writers[i] = nil
    20  		}
    21  	}
    22  
    23  	// consolidate the slice
    24  	for i := 0; i < len(mw.writers); i++ {
    25  		if mw.writers[i] != nil {
    26  			continue
    27  		}
    28  
    29  		j := len(mw.writers) - 1
    30  		for ; j > i; j-- {
    31  			if mw.writers[j] != nil {
    32  				mw.writers[i], mw.writers[j] = mw.writers[j], nil // swap
    33  				break
    34  			}
    35  		}
    36  		mw.writers = mw.writers[:j]
    37  	}
    38  	mw.lk.Unlock()
    39  	return len(b), nil
    40  }
    41  
    42  func (mw *MirrorWriter) AddWriter(w io.Writer) {
    43  	mw.lk.Lock()
    44  	mw.writers = append(mw.writers, w)
    45  	mw.lk.Unlock()
    46  }
    47  
    48  func (mw *MirrorWriter) Active() (active bool) {
    49  	mw.lk.Lock()
    50  	active = len(mw.writers) > 0
    51  	mw.lk.Unlock()
    52  	return
    53  }