github.com/argoproj/argo-events@v1.9.1/pkg/apis/common/int64str.go (about) 1 package common 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "strconv" 7 ) 8 9 type Int64OrString struct { 10 Type Type `json:"type" protobuf:"varint,1,opt,name=type,casttype=Type"` 11 Int64Val int64 `json:"int64Val,omitempty" protobuf:"varint,2,opt,name=int64Val"` 12 StrVal string `json:"strVal,omitempty" protobuf:"bytes,3,opt,name=strVal"` 13 } 14 15 // Type represents the stored type of Int64OrString. 16 type Type int64 17 18 const ( 19 Int64 Type = iota // The Int64OrString holds an int64. 20 String // The Int64OrString holds a string. 21 ) 22 23 // FromString creates an Int64OrString object with a string value. 24 func FromString(val string) Int64OrString { 25 return Int64OrString{Type: String, StrVal: val} 26 } 27 28 // FromInt64 creates an Int64OrString object with an int64 value. 29 func FromInt64(val int64) Int64OrString { 30 return Int64OrString{Type: Int64, Int64Val: val} 31 } 32 33 // Parse the given string and try to convert it to an int64 before 34 // setting it as a string value. 35 func Parse(val string) Int64OrString { 36 i, err := strconv.ParseInt(val, 10, 64) 37 if err != nil { 38 return FromString(val) 39 } 40 return FromInt64(i) 41 } 42 43 // UnmarshalJSON implements the json.Unmarshaller interface. 44 func (int64str *Int64OrString) UnmarshalJSON(value []byte) error { 45 if value[0] == '"' { 46 int64str.Type = String 47 return json.Unmarshal(value, &int64str.StrVal) 48 } 49 int64str.Type = Int64 50 return json.Unmarshal(value, &int64str.Int64Val) 51 } 52 53 // Int64Value returns the Int64Val if type Int64, or if 54 // it is a String, will attempt a conversion to int64, 55 // returning 0 if a parsing error occurs. 56 func (int64str *Int64OrString) Int64Value() int64 { 57 if int64str.Type == String { 58 i, _ := strconv.ParseInt(int64str.StrVal, 10, 64) 59 return i 60 } 61 return int64str.Int64Val 62 } 63 64 // MarshalJSON implements the json.Marshaller interface. 65 func (int64str Int64OrString) MarshalJSON() ([]byte, error) { 66 switch int64str.Type { 67 case Int64: 68 return json.Marshal(int64str.Int64Val) 69 case String: 70 return json.Marshal(int64str.StrVal) 71 default: 72 return []byte{}, fmt.Errorf("impossible Int64OrString.Type") 73 } 74 } 75 76 // OpenAPISchemaType is used by the kube-openapi generator when constructing 77 // the OpenAPI spec of this type. 78 // 79 // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators 80 func (Int64OrString) OpenAPISchemaType() []string { return []string{"string"} } 81 82 // OpenAPISchemaFormat is used by the kube-openapi generator when constructing 83 // the OpenAPI spec of this type. 84 func (Int64OrString) OpenAPISchemaFormat() string { return "int64-or-string" }