github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/pipes/streams/write.go (about)

     1  package streams
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/lmorg/murex/lang/stdio"
     7  	"github.com/lmorg/murex/utils"
     8  )
     9  
    10  // Write is the standard Writer interface Write() method.
    11  func (stdin *Stdin) Write(p []byte) (int, error) {
    12  	if len(p) == 0 {
    13  		return 0, nil
    14  	}
    15  
    16  	for {
    17  		select {
    18  		case <-stdin.ctx.Done():
    19  			stdin.mutex.Lock()
    20  			stdin.buffer = []byte{}
    21  			stdin.mutex.Unlock()
    22  			return 0, io.ErrClosedPipe
    23  		default:
    24  		}
    25  
    26  		//stdin.mutex.RLock()
    27  		stdin.mutex.Lock()
    28  		buffSize := len(stdin.buffer)
    29  		maxBufferSize := stdin.max
    30  		//stdin.mutex.RUnlock()
    31  		stdin.mutex.Unlock()
    32  
    33  		if buffSize < maxBufferSize || maxBufferSize == 0 {
    34  			break
    35  		}
    36  	}
    37  
    38  	stdin.mutex.Lock()
    39  	stdin.buffer = appendBytes(stdin.buffer, p...)
    40  	stdin.bWritten += uint64(len(p))
    41  	stdin.mutex.Unlock()
    42  
    43  	return len(p), nil
    44  }
    45  
    46  // Writeln just calls Write() but with an appended, OS specific, new line.
    47  func (stdin *Stdin) Writeln(b []byte) (int, error) {
    48  	return stdin.Write(appendBytes(b, utils.NewLineByte...))
    49  }
    50  
    51  // WriteArray performs data type specific buffered writes to an stdio.Io interface
    52  func (stdin *Stdin) WriteArray(dataType string) (stdio.ArrayWriter, error) {
    53  	return stdio.WriteArray(stdin, dataType)
    54  }
    55  
    56  // ReadFrom reads data from r until EOF and appends it to the buffer.
    57  func (stdin *Stdin) ReadFrom(r io.Reader) (int64, error) {
    58  	var total int64
    59  
    60  	stdin.mutex.Lock()
    61  	stdin.max = 0
    62  	stdin.mutex.Unlock()
    63  
    64  	var rErr, wErr error
    65  	i := 0
    66  
    67  	for {
    68  		select {
    69  		case <-stdin.ctx.Done():
    70  			return total, io.ErrClosedPipe
    71  
    72  		default:
    73  			p := make([]byte, 1024)
    74  			i, rErr = r.Read(p)
    75  
    76  			if rErr != nil && rErr != io.EOF {
    77  				return total, rErr
    78  			}
    79  
    80  			i, wErr = stdin.Write(p[:i])
    81  			if wErr != nil {
    82  				return total, wErr
    83  			}
    84  
    85  			total += int64(i)
    86  			if rErr == io.EOF {
    87  				return total, nil
    88  			}
    89  		}
    90  	}
    91  }