gitlab.com/evatix-go/core@v1.3.55/coredata/coreonce/BoolOnce.go (about)

     1  package coreonce
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  )
     7  
     8  type BoolOnce struct {
     9  	innerData       bool
    10  	initializerFunc func() bool
    11  	isInitialized   bool
    12  }
    13  
    14  func NewBoolOnce(initializerFunc func() bool) BoolOnce {
    15  	return BoolOnce{
    16  		initializerFunc: initializerFunc,
    17  	}
    18  }
    19  
    20  func NewBoolOncePtr(initializerFunc func() bool) *BoolOnce {
    21  	return &BoolOnce{
    22  		initializerFunc: initializerFunc,
    23  	}
    24  }
    25  
    26  func (it *BoolOnce) MarshalJSON() ([]byte, error) {
    27  	return json.Marshal(it.Value())
    28  }
    29  
    30  func (it *BoolOnce) UnmarshalJSON(data []byte) error {
    31  	it.isInitialized = true
    32  
    33  	return json.Unmarshal(data, &it.innerData)
    34  }
    35  
    36  func (it *BoolOnce) Value() bool {
    37  	if it.isInitialized {
    38  		return it.innerData
    39  	}
    40  
    41  	it.innerData = it.initializerFunc()
    42  	it.isInitialized = true
    43  
    44  	return it.innerData
    45  }
    46  
    47  func (it *BoolOnce) Execute() bool {
    48  	return it.Value()
    49  }
    50  
    51  func (it *BoolOnce) String() string {
    52  	return strconv.FormatBool(it.Value())
    53  }
    54  
    55  func (it *BoolOnce) Serialize() ([]byte, error) {
    56  	value := it.Value()
    57  
    58  	return json.Marshal(value)
    59  }