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

     1  package coreonce
     2  
     3  import (
     4  	"encoding/json"
     5  )
     6  
     7  type BytesOnce struct {
     8  	innerData       []byte
     9  	initializerFunc func() []byte
    10  	isInitialized   bool
    11  }
    12  
    13  func NewBytesOnce(initializerFunc func() []byte) BytesOnce {
    14  	return BytesOnce{
    15  		initializerFunc: initializerFunc,
    16  	}
    17  }
    18  
    19  func NewBytesOncePtr(initializerFunc func() []byte) *BytesOnce {
    20  	return &BytesOnce{
    21  		initializerFunc: initializerFunc,
    22  	}
    23  }
    24  
    25  func (it *BytesOnce) MarshalJSON() ([]byte, error) {
    26  	return json.Marshal(it.Value())
    27  }
    28  
    29  func (it *BytesOnce) UnmarshalJSON(data []byte) error {
    30  	it.isInitialized = true
    31  
    32  	return json.Unmarshal(data, &it.innerData)
    33  }
    34  
    35  func (it *BytesOnce) Value() []byte {
    36  	if it.isInitialized {
    37  		return it.innerData
    38  	}
    39  
    40  	it.innerData = it.initializerFunc()
    41  	it.isInitialized = true
    42  
    43  	return it.innerData
    44  }
    45  
    46  func (it *BytesOnce) Execute() []byte {
    47  	return it.Value()
    48  }
    49  
    50  // IsEmpty returns true if zero
    51  func (it *BytesOnce) IsEmpty() bool {
    52  	return it == nil || it.initializerFunc == nil || len(it.Value()) == 0
    53  }
    54  
    55  func (it *BytesOnce) String() string {
    56  	return string(it.Value())
    57  }
    58  
    59  func (it *BytesOnce) Length() int {
    60  	if it == nil || it.initializerFunc == nil {
    61  		return 0
    62  	}
    63  
    64  	return len(it.Value())
    65  }
    66  
    67  func (it *BytesOnce) Serialize() ([]byte, error) {
    68  	value := it.Value()
    69  
    70  	return json.Marshal(value)
    71  }