golang.org/x/build@v0.0.0-20240506185731-218518f32b70/kubernetes/api/util.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 api
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"strconv"
    23  )
    24  
    25  // IntOrString is a type that can hold an int or a string.  When used in
    26  // JSON or YAML marshalling and unmarshalling, it produces or consumes the
    27  // inner type.  This allows you to have, for example, a JSON field that can
    28  // accept a name or number.
    29  type IntOrString struct {
    30  	Kind   IntstrKind
    31  	IntVal int
    32  	StrVal string
    33  }
    34  
    35  // IntstrKind represents the stored type of IntOrString.
    36  type IntstrKind int
    37  
    38  const (
    39  	IntstrInt    IntstrKind = iota // The IntOrString holds an int.
    40  	IntstrString                   // The IntOrString holds a string.
    41  )
    42  
    43  // UnmarshalJSON implements the json.Unmarshaller interface.
    44  func (intstr *IntOrString) UnmarshalJSON(value []byte) error {
    45  	if value[0] == '"' {
    46  		intstr.Kind = IntstrString
    47  		return json.Unmarshal(value, &intstr.StrVal)
    48  	}
    49  	intstr.Kind = IntstrInt
    50  	return json.Unmarshal(value, &intstr.IntVal)
    51  }
    52  
    53  // String returns the string value, or Itoa's the int value.
    54  func (intstr *IntOrString) String() string {
    55  	if intstr.Kind == IntstrString {
    56  		return intstr.StrVal
    57  	}
    58  	return strconv.Itoa(intstr.IntVal)
    59  }
    60  
    61  // MarshalJSON implements the json.Marshaller interface.
    62  func (intstr IntOrString) MarshalJSON() ([]byte, error) {
    63  	switch intstr.Kind {
    64  	case IntstrInt:
    65  		return json.Marshal(intstr.IntVal)
    66  	case IntstrString:
    67  		return json.Marshal(intstr.StrVal)
    68  	default:
    69  		return []byte{}, fmt.Errorf("impossible IntOrString.Kind")
    70  	}
    71  }
    72  
    73  // UID is a type that holds unique ID values, including UUIDs.  Because we
    74  // don't ONLY use UUIDs, this is an alias to string.  Being a type captures
    75  // intent and helps make sure that UIDs and names do not get conflated.
    76  type UID string