github.com/haraldrudell/parl@v0.4.176/t-result.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  // TFunc is a function that returns value, err and may panic
     9  type TFunc[T any] func() (value T, err error)
    10  
    11  // TResult is a value-container for value, isPanic and error
    12  type TResult[T any] struct {
    13  	Value   T
    14  	IsPanic bool
    15  	Err     error
    16  }
    17  
    18  // NewTResult3 creates a TResult from pointers at the time values are available
    19  //   - value is considered valid if errp is nil or *errp is nil
    20  //   - any arguments may be nil
    21  func NewTResult3[T any](value *T, isPanic *bool, errp *error) (tResult *TResult[T]) {
    22  	var result TResult[T]
    23  	tResult = &result
    24  	if errp != nil {
    25  		if err := *errp; err != nil {
    26  			result.Err = err
    27  			if isPanic != nil {
    28  				result.IsPanic = *isPanic
    29  			}
    30  		}
    31  	}
    32  	if result.Err == nil && value != nil {
    33  		result.Value = *value
    34  	}
    35  	return
    36  }
    37  
    38  // NewTResult creates a result container
    39  //   - if tFunc is present, it is invoked prior to returning storing its result
    40  //   - recovers tFunc panic
    41  func NewTResult[T any](tFunc ...TFunc[T]) (tResult *TResult[T]) {
    42  
    43  	// create result object
    44  	var t TResult[T]
    45  	tResult = &t
    46  
    47  	// check if tFunc is available
    48  	var f TFunc[T]
    49  	if len(tFunc) > 0 {
    50  		f = tFunc[0]
    51  	}
    52  	if f == nil {
    53  		return // tFunc not present return
    54  	}
    55  
    56  	// execute tFunc
    57  	defer RecoverErr(func() DA { return A() }, &t.Err, &t.IsPanic)
    58  
    59  	t.Value, t.Err = f()
    60  
    61  	return // tFunc completed return
    62  }