k8s.io/kube-openapi@v0.0.0-20240228011516-70dd3763d340/pkg/internal/serialization.go (about)

     1  /*
     2  Copyright 2023 The Kubernetes Authors.
     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 internal
    18  
    19  import (
    20  	"github.com/go-openapi/jsonreference"
    21  	jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json"
    22  )
    23  
    24  // DeterministicMarshal calls the jsonv2 library with the deterministic
    25  // flag in order to have stable marshaling.
    26  func DeterministicMarshal(in any) ([]byte, error) {
    27  	return jsonv2.MarshalOptions{Deterministic: true}.Marshal(jsonv2.EncodeOptions{}, in)
    28  }
    29  
    30  // JSONRefFromMap populates a json reference object if the map v contains a $ref key.
    31  func JSONRefFromMap(jsonRef *jsonreference.Ref, v map[string]interface{}) error {
    32  	if v == nil {
    33  		return nil
    34  	}
    35  	if vv, ok := v["$ref"]; ok {
    36  		if str, ok := vv.(string); ok {
    37  			ref, err := jsonreference.New(str)
    38  			if err != nil {
    39  				return err
    40  			}
    41  			*jsonRef = ref
    42  		}
    43  	}
    44  	return nil
    45  }
    46  
    47  // SanitizeExtensions sanitizes the input map such that non extension
    48  // keys (non x-*, X-*) keys are dropped from the map. Returns the new
    49  // modified map, or nil if the map is now empty.
    50  func SanitizeExtensions(e map[string]interface{}) map[string]interface{} {
    51  	for k := range e {
    52  		if !IsExtensionKey(k) {
    53  			delete(e, k)
    54  		}
    55  	}
    56  	if len(e) == 0 {
    57  		e = nil
    58  	}
    59  	return e
    60  }
    61  
    62  // IsExtensionKey returns true if the input string is of format x-* or X-*
    63  func IsExtensionKey(k string) bool {
    64  	return len(k) > 1 && (k[0] == 'x' || k[0] == 'X') && k[1] == '-'
    65  }