codeberg.org/gruf/go-format@v1.0.6/print.go (about)

     1  package format
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"sync"
     7  )
     8  
     9  // pool is the global printer buffer pool.
    10  var pool = sync.Pool{
    11  	New: func() interface{} {
    12  		return &Buffer{}
    13  	},
    14  }
    15  
    16  // getBuf fetches a buffer from pool.
    17  func getBuf() *Buffer {
    18  	return pool.Get().(*Buffer)
    19  }
    20  
    21  // putBuf places a Buffer back in pool.
    22  func putBuf(buf *Buffer) {
    23  	if buf.Cap() > 64<<10 {
    24  		return // drop large
    25  	}
    26  	buf.Reset()
    27  	pool.Put(buf)
    28  }
    29  
    30  // Sprint will format supplied values, returning this string.
    31  func Sprint(v ...interface{}) string {
    32  	buf := Buffer{}
    33  	Append(&buf, v...)
    34  	return buf.String()
    35  }
    36  
    37  // Sprintf will format supplied format string and args, returning this string.
    38  // See Formatter.Appendf() for more documentation.
    39  func Sprintf(s string, a ...interface{}) string {
    40  	buf := Buffer{}
    41  	Appendf(&buf, s, a...)
    42  	return buf.String()
    43  }
    44  
    45  // Print will format supplied values, print this to os.Stdout.
    46  func Print(v ...interface{}) {
    47  	_, _ = Fprint(os.Stdout, v...)
    48  }
    49  
    50  // Printf will format supplied format string and args, printing this to os.Stdout.
    51  // See Formatter.Appendf() for more documentation.
    52  func Printf(s string, a ...interface{}) {
    53  	_, _ = Fprintf(os.Stdout, s, a...)
    54  }
    55  
    56  // Println will format supplied values, append a trailing newline and print this to os.Stdout.
    57  func Println(v ...interface{}) {
    58  	_, _ = Fprintln(os.Stdout, v...)
    59  }
    60  
    61  // Fprint will format supplied values, writing this to an io.Writer.
    62  func Fprint(w io.Writer, v ...interface{}) (int, error) {
    63  	buf := getBuf()
    64  	Append(buf, v...)
    65  	n, err := w.Write(buf.B)
    66  	putBuf(buf)
    67  	return n, err
    68  }
    69  
    70  // Fprintf will format supplied format string and args, writing this to an io.Writer.
    71  // See Formatter.Appendf() for more documentation.
    72  func Fprintf(w io.Writer, s string, a ...interface{}) (int, error) {
    73  	buf := getBuf()
    74  	Appendf(buf, s, a...)
    75  	n, err := w.Write(buf.B)
    76  	putBuf(buf)
    77  	return n, err
    78  }
    79  
    80  // Println will format supplied values, append a trailing newline and writer this to an io.Writer.
    81  func Fprintln(w io.Writer, v ...interface{}) (int, error) {
    82  	buf := getBuf()
    83  	Append(buf, v...)
    84  	buf.AppendByte('\n')
    85  	n, err := w.Write(buf.B)
    86  	putBuf(buf)
    87  	return n, err
    88  }