github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/bufio/race.go (about)

     1  package bufio
     2  
     3  import (
     4  	"io"
     5  	"sync"
     6  
     7  	"github.com/sagernet/sing/common/buf"
     8  	N "github.com/sagernet/sing/common/network"
     9  )
    10  
    11  type RaceWriter struct {
    12  	upstream N.ExtendedWriter
    13  	access   sync.Mutex
    14  }
    15  
    16  func NewRaceWriter(writer io.Writer) *RaceWriter {
    17  	return &RaceWriter{
    18  		upstream: NewExtendedWriter(writer),
    19  	}
    20  }
    21  
    22  func (w *RaceWriter) WriteBuffer(buffer *buf.Buffer) error {
    23  	w.access.Lock()
    24  	defer w.access.Unlock()
    25  	return w.upstream.WriteBuffer(buffer)
    26  }
    27  
    28  func (w *RaceWriter) Write(p []byte) (n int, err error) {
    29  	w.access.Lock()
    30  	defer w.access.Unlock()
    31  	return w.upstream.Write(p)
    32  }
    33  
    34  func (w *RaceWriter) Upstream() any {
    35  	return w.upstream
    36  }