github.com/NVIDIA/aistore@v1.3.23-0.20240517131212-7df6609be51d/cmn/nlog/fixedbuf.go (about)

     1  // Package nlog - aistore logger, provides buffering, timestamping, writing, and
     2  // flushing/syncing/rotating
     3  /*
     4   * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
     5   */
     6  package nlog
     7  
     8  import (
     9  	"io"
    10  	"os"
    11  )
    12  
    13  type fixed struct {
    14  	buf  []byte
    15  	woff int
    16  }
    17  
    18  // interface guard
    19  var _ io.Writer = (*fixed)(nil)
    20  
    21  func (fb *fixed) Write(p []byte) (int, error) {
    22  	n := copy(fb.buf[fb.woff:], p)
    23  	fb.woff += n
    24  	return len(p), nil // silent discard
    25  }
    26  
    27  // private
    28  
    29  func (fb *fixed) writeString(p string) {
    30  	n := copy(fb.buf[fb.woff:], p)
    31  	fb.woff += n
    32  }
    33  
    34  func (fb *fixed) writeByte(c byte) {
    35  	if fb.avail() > 0 {
    36  		fb.buf[fb.woff] = c
    37  		fb.woff++
    38  	}
    39  }
    40  
    41  func (fb *fixed) flush(file *os.File) (n int, err error) {
    42  	n, err = file.Write(fb.buf[:fb.woff])
    43  	if err != nil {
    44  		if Stopping() {
    45  			_whileStopping(fb.buf[:fb.woff])
    46  			return 0, nil
    47  		}
    48  		os.Stderr.WriteString(err.Error() + "\n")
    49  	}
    50  	return
    51  }
    52  
    53  func (fb *fixed) reset()      { fb.woff = 0 }
    54  func (fb *fixed) length() int { return fb.woff }
    55  func (fb *fixed) size() int   { return cap(fb.buf) }
    56  func (fb *fixed) avail() int  { return cap(fb.buf) - fb.woff }
    57  
    58  func (fb *fixed) eol() {
    59  	if fb.woff == 0 || (fb.buf[fb.woff-1] != '\n' && fb.avail() > 0) {
    60  		fb.buf[fb.woff] = '\n'
    61  		fb.woff++
    62  	}
    63  }