github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/intstr/intstr.go (about) 1 /* 2 Copyright 2014 The Kubernetes Authors All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package intstr 18 19 import ( 20 "encoding/json" 21 "fmt" 22 "strconv" 23 24 "github.com/google/gofuzz" 25 ) 26 27 // IntOrString is a type that can hold an int or a string. When used in 28 // JSON or YAML marshalling and unmarshalling, it produces or consumes the 29 // inner type. This allows you to have, for example, a JSON field that can 30 // accept a name or number. 31 type IntOrString struct { 32 Type Type 33 IntVal int 34 StrVal string 35 } 36 37 // Type represents the stored type of IntOrString. 38 type Type int 39 40 const ( 41 Int Type = iota // The IntOrString holds an int. 42 String // The IntOrString holds a string. 43 ) 44 45 // FromInt creates an IntOrString object with an int value. 46 func FromInt(val int) IntOrString { 47 return IntOrString{Type: Int, IntVal: val} 48 } 49 50 // FromString creates an IntOrString object with a string value. 51 func FromString(val string) IntOrString { 52 return IntOrString{Type: String, StrVal: val} 53 } 54 55 // UnmarshalJSON implements the json.Unmarshaller interface. 56 func (intstr *IntOrString) UnmarshalJSON(value []byte) error { 57 if value[0] == '"' { 58 intstr.Type = String 59 return json.Unmarshal(value, &intstr.StrVal) 60 } 61 intstr.Type = Int 62 return json.Unmarshal(value, &intstr.IntVal) 63 } 64 65 // String returns the string value, or the Itoa of the int value. 66 func (intstr *IntOrString) String() string { 67 if intstr.Type == String { 68 return intstr.StrVal 69 } 70 return strconv.Itoa(intstr.IntVal) 71 } 72 73 // MarshalJSON implements the json.Marshaller interface. 74 func (intstr IntOrString) MarshalJSON() ([]byte, error) { 75 switch intstr.Type { 76 case Int: 77 return json.Marshal(intstr.IntVal) 78 case String: 79 return json.Marshal(intstr.StrVal) 80 default: 81 return []byte{}, fmt.Errorf("impossible IntOrString.Type") 82 } 83 } 84 85 func (intstr *IntOrString) Fuzz(c fuzz.Continue) { 86 if intstr == nil { 87 return 88 } 89 if c.RandBool() { 90 intstr.Type = Int 91 c.Fuzz(&intstr.IntVal) 92 intstr.StrVal = "" 93 } else { 94 intstr.Type = String 95 intstr.IntVal = 0 96 c.Fuzz(&intstr.StrVal) 97 } 98 }