github.com/arnodel/golua@v0.0.0-20230215163904-e0b5347eaaa1/lib/iolib/buffers.go (about)

     1  package iolib
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"errors"
     7  	"io"
     8  )
     9  
    10  type bufReader interface {
    11  	io.Reader
    12  	Reset(r io.Reader)
    13  	Buffered() int
    14  	Discard(int) (int, error)
    15  	Peek(n int) ([]byte, error)
    16  	ReadString(delim byte) (string, error)
    17  }
    18  
    19  type bufWriter interface {
    20  	io.Writer
    21  	Reset(w io.Writer)
    22  	Flush() error
    23  }
    24  type nobufReader struct {
    25  	io.Reader
    26  }
    27  
    28  var (
    29  	_ bufReader = (*nobufReader)(nil)
    30  	_ bufReader = (*bufio.Reader)(nil)
    31  	_ bufWriter = (*nobufWriter)(nil)
    32  	_ bufWriter = (*bufio.Writer)(nil)
    33  )
    34  
    35  func (u *nobufReader) Reset(r io.Reader) {
    36  	u.Reader = r
    37  }
    38  
    39  func (u *nobufReader) Buffered() int {
    40  	return 0
    41  }
    42  
    43  func (u *nobufReader) Discard(n int) (int, error) {
    44  	if n > 0 {
    45  		return 0, errors.New("nobufReader cannot discard")
    46  	}
    47  	return 0, nil
    48  }
    49  
    50  func (u *nobufReader) Peek(n int) ([]byte, error) {
    51  	if n > 0 {
    52  		return nil, errors.New("nobufReader cannot peek")
    53  	}
    54  	return nil, nil
    55  }
    56  
    57  func (u *nobufReader) ReadString(delim byte) (string, error) {
    58  	return "", errors.New("unimplemented")
    59  }
    60  
    61  type nobufWriter struct {
    62  	io.Writer
    63  }
    64  
    65  func (u *nobufWriter) Reset(w io.Writer) {
    66  	u.Writer = w
    67  }
    68  
    69  func (u *nobufWriter) Flush() error {
    70  	return nil
    71  }
    72  
    73  type linebufWriter struct {
    74  	*bufio.Writer
    75  }
    76  
    77  func (u linebufWriter) Write(p []byte) (n int, err error) {
    78  	for len(p) > 0 {
    79  		i := bytes.IndexAny(p, "\n\r") + 1
    80  		flush := i > 0
    81  		if !flush {
    82  			i = len(p)
    83  		}
    84  		m, err := u.Writer.Write(p[:i])
    85  		n += m
    86  		if err == nil && flush {
    87  			err = u.Flush()
    88  		}
    89  		if err != nil {
    90  			break
    91  		}
    92  		p = p[i:]
    93  	}
    94  	return n, err
    95  }