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

     1  package net
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"fmt"
     7  	"io"
     8  
     9  	"github.com/lmorg/murex/builtins/pipes/streams"
    10  	"github.com/lmorg/murex/config"
    11  	"github.com/lmorg/murex/lang/stdio"
    12  	"github.com/lmorg/murex/utils"
    13  )
    14  
    15  // Read bytes from net Io interface
    16  func (n *Net) Read(p []byte) (i int, err error) {
    17  	select {
    18  	case <-n.ctx.Done():
    19  		return 0, io.EOF
    20  	default:
    21  	}
    22  
    23  	i, err = n.conn.Read(p)
    24  	n.mutex.Lock()
    25  	n.bRead += uint64(i)
    26  	n.mutex.Unlock()
    27  	return
    28  }
    29  
    30  // ReadLine reads a line from net Io interface
    31  func (n *Net) ReadLine(callback func([]byte)) error {
    32  	scanner := bufio.NewScanner(n)
    33  	for scanner.Scan() {
    34  		b := scanner.Bytes()
    35  		n.mutex.Lock()
    36  		n.bRead += uint64(len(b))
    37  		n.mutex.Unlock()
    38  		callback(append(scanner.Bytes(), utils.NewLineByte...))
    39  	}
    40  
    41  	err := scanner.Err()
    42  	if err != nil {
    43  		return fmt.Errorf("error while ReadLine on network pipe: %s", err.Error())
    44  	}
    45  	return nil
    46  }
    47  
    48  // ReadAll data from net Io interface
    49  func (n *Net) ReadAll() (b []byte, err error) {
    50  	w := streams.NewStdinWithContext(n.ctx, n.forceClose)
    51  
    52  	_, err = w.ReadFrom(n.conn)
    53  	if err != nil {
    54  		return
    55  	}
    56  
    57  	b, err = w.ReadAll()
    58  
    59  	n.mutex.Lock()
    60  	n.bRead += uint64(len(b))
    61  	n.mutex.Unlock()
    62  
    63  	return
    64  }
    65  
    66  // ReadArray treats net Io interface as an array of data
    67  func (n *Net) ReadArray(ctx context.Context, callback func([]byte)) error {
    68  	return stdio.ReadArray(ctx, n, callback)
    69  }
    70  
    71  // ReadArrayWithType treats net Io interface as an array of data
    72  func (n *Net) ReadArrayWithType(ctx context.Context, callback func(interface{}, string)) error {
    73  	return stdio.ReadArrayWithType(ctx, n, callback)
    74  }
    75  
    76  // ReadMap treats net Io interface as an hash of data
    77  func (n *Net) ReadMap(config *config.Config, callback func(*stdio.Map)) error {
    78  	return stdio.ReadMap(n, config, callback)
    79  }