github.com/pingcap/tidb-lightning@v5.0.0-rc.0.20210428090220-84b649866577+incompatible/lightning/common/once_error.go (about)

     1  // Copyright 2019 PingCAP, 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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package common
    15  
    16  import (
    17  	"sync"
    18  )
    19  
    20  // OnceError is an error value which will can be assigned once.
    21  //
    22  // The zero value is ready for use.
    23  type OnceError struct {
    24  	lock sync.Mutex
    25  	err  error
    26  }
    27  
    28  // Set assigns an error to this instance, if `e != nil`.
    29  //
    30  // If this method is called multiple times, only the first call is effective.
    31  func (oe *OnceError) Set(e error) {
    32  	if e != nil {
    33  		oe.lock.Lock()
    34  		if oe.err == nil {
    35  			oe.err = e
    36  		}
    37  		oe.lock.Unlock()
    38  	}
    39  }
    40  
    41  // Get returns the first error value stored in this instance.
    42  func (oe *OnceError) Get() error {
    43  	oe.lock.Lock()
    44  	defer oe.lock.Unlock()
    45  	return oe.err
    46  }