gitlab.com/evatix-go/core@v1.3.55/coredata/coreonce/ByteOnce.go (about) 1 package coreonce 2 3 import ( 4 "encoding/json" 5 "strconv" 6 ) 7 8 type ByteOnce struct { 9 innerData byte 10 initializerFunc func() byte 11 isInitialized bool 12 } 13 14 func NewByteOnce(initializerFunc func() byte) ByteOnce { 15 return ByteOnce{ 16 initializerFunc: initializerFunc, 17 } 18 } 19 20 func NewByteOncePtr(initializerFunc func() byte) *ByteOnce { 21 return &ByteOnce{ 22 initializerFunc: initializerFunc, 23 } 24 } 25 26 func (it *ByteOnce) MarshalJSON() ([]byte, error) { 27 return json.Marshal(it.Value()) 28 } 29 30 func (it *ByteOnce) UnmarshalJSON(data []byte) error { 31 it.isInitialized = true 32 33 return json.Unmarshal(data, &it.innerData) 34 } 35 36 func (it *ByteOnce) Value() byte { 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 *ByteOnce) Execute() byte { 48 return it.Value() 49 } 50 51 func (it *ByteOnce) Int() int { 52 return int(it.Value()) 53 } 54 55 // IsEmpty returns true if zero 56 func (it *ByteOnce) IsEmpty() bool { 57 return it.Value() == 0 58 } 59 60 func (it *ByteOnce) IsZero() bool { 61 return it.Value() == 0 62 } 63 64 func (it *ByteOnce) IsNegative() bool { 65 return it.Value() < 0 66 } 67 68 func (it *ByteOnce) IsPositive() bool { 69 return it.Value() > 0 70 } 71 72 func (it *ByteOnce) String() string { 73 return strconv.Itoa(int(it.Value())) 74 } 75 76 func (it *ByteOnce) Serialize() ([]byte, error) { 77 value := it.Value() 78 79 return json.Marshal(value) 80 }