github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/store/atomicerr/atomic_error.go (about)

     1  // Copyright 2019 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package atomicerr
    16  
    17  import (
    18  	"sync"
    19  	"sync/atomic"
    20  )
    21  
    22  type AtomicError struct {
    23  	once *sync.Once
    24  	val  *atomic.Value
    25  }
    26  
    27  func New() *AtomicError {
    28  	return &AtomicError{&sync.Once{}, &atomic.Value{}}
    29  }
    30  
    31  func (ae *AtomicError) SetIfError(err error) bool {
    32  	if err != nil {
    33  		ae.once.Do(func() {
    34  			ae.val.Store(err)
    35  		})
    36  
    37  		return true
    38  	}
    39  
    40  	return false
    41  }
    42  
    43  func (ae *AtomicError) SetIfErrAndCheck(err error) bool {
    44  	ae.SetIfError(err)
    45  	return ae.IsSet()
    46  }
    47  
    48  func (ae *AtomicError) IsSet() bool {
    49  	val := ae.val.Load()
    50  	return val != nil
    51  }
    52  
    53  func (ae *AtomicError) Get() error {
    54  	val := ae.val.Load()
    55  
    56  	if val == nil {
    57  		return nil
    58  	}
    59  
    60  	return val.(error)
    61  }
    62  
    63  func (ae *AtomicError) Error() string {
    64  	err := ae.Get()
    65  
    66  	if err != nil {
    67  		return err.Error()
    68  	}
    69  
    70  	return ""
    71  }