github.com/containerd/nerdctl@v1.7.7/pkg/reflectutil/reflectutil.go (about)

     1  /*
     2     Copyright The containerd 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 reflectutil
    18  
    19  import (
    20  	"fmt"
    21  	"reflect"
    22  )
    23  
    24  func UnknownNonEmptyFields(structOrStructPtr interface{}, knownNames ...string) []string {
    25  	var unknown []string
    26  	knownNamesMap := make(map[string]struct{}, len(knownNames))
    27  	for _, name := range knownNames {
    28  		knownNamesMap[name] = struct{}{}
    29  	}
    30  	origVal := reflect.ValueOf(structOrStructPtr)
    31  	var val reflect.Value
    32  	switch kind := origVal.Kind(); kind {
    33  	case reflect.Ptr:
    34  		val = origVal.Elem()
    35  	case reflect.Struct:
    36  		val = origVal
    37  	default:
    38  		panic(fmt.Errorf("expected Ptr or Struct, got %+v", kind))
    39  	}
    40  	for i := 0; i < val.NumField(); i++ {
    41  		iField := val.Field(i)
    42  		if isEmpty(iField) {
    43  			continue
    44  		}
    45  		iName := val.Type().Field(i).Name
    46  		if _, ok := knownNamesMap[iName]; !ok {
    47  			unknown = append(unknown, iName)
    48  		}
    49  	}
    50  	return unknown
    51  }
    52  
    53  func isEmpty(v reflect.Value) bool {
    54  	// NOTE: IsZero returns false for zero-length map and slice
    55  	if v.IsZero() {
    56  		return true
    57  	}
    58  	switch v.Kind() {
    59  	case reflect.Map, reflect.Slice:
    60  		return v.Len() == 0
    61  	}
    62  	return false
    63  }