github.com/haraldrudell/parl@v0.4.176/mains/err-store.go (about)

     1  /*
     2  © 2024–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package mains
     7  
     8  import (
     9  	"slices"
    10  	"sync"
    11  	"sync/atomic"
    12  
    13  	"github.com/haraldrudell/parl"
    14  )
    15  
    16  // errStore is a slice to distinguish multiple invocations of AddErr
    17  //   - must be initialization free
    18  //   - must be thread-safe
    19  type errStore struct {
    20  	errsLock    sync.Mutex
    21  	errs        []error
    22  	count       parl.Atomic64[int]
    23  	IsFirstLong atomic.Bool
    24  }
    25  
    26  func (e *errStore) Count() (count int) { return e.count.Load() }
    27  
    28  func (e *errStore) Add(err error) {
    29  	e.errsLock.Lock()
    30  	defer e.errsLock.Unlock()
    31  
    32  	e.errs = append(e.errs, err)
    33  	e.count.Add(1)
    34  }
    35  
    36  func (e *errStore) GetN(index ...int) (err error) {
    37  	e.errsLock.Lock()
    38  	defer e.errsLock.Unlock()
    39  
    40  	var i int
    41  	if len(index) > 0 {
    42  		i = index[0]
    43  	}
    44  	if i >= 0 && i < len(e.errs) {
    45  		err = e.errs[i]
    46  	}
    47  	return
    48  }
    49  
    50  func (e *errStore) Get() (errs []error) {
    51  	e.errsLock.Lock()
    52  	defer e.errsLock.Unlock()
    53  
    54  	errs = slices.Clone(e.errs)
    55  	return
    56  }