Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/reflectutil/reflectutil.go
2604 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
// This file has been adapted from https://github.com/containerd/nerdctl/blob/v1.0.0/pkg/reflectutil/reflectutil.go
5
/*
6
Copyright The containerd Authors.
7
Licensed under the Apache License, Version 2.0 (the "License");
8
you may not use this file except in compliance with the License.
9
You may obtain a copy of the License at
10
http://www.apache.org/licenses/LICENSE-2.0
11
Unless required by applicable law or agreed to in writing, software
12
distributed under the License is distributed on an "AS IS" BASIS,
13
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
See the License for the specific language governing permissions and
15
limitations under the License.
16
*/
17
18
package reflectutil
19
20
import (
21
"fmt"
22
"reflect"
23
)
24
25
func UnknownNonEmptyFields(structOrStructPtr any, knownNames ...string) []string {
26
var unknown []string
27
knownNamesMap := make(map[string]struct{}, len(knownNames))
28
for _, name := range knownNames {
29
knownNamesMap[name] = struct{}{}
30
}
31
origVal := reflect.ValueOf(structOrStructPtr)
32
var val reflect.Value
33
switch kind := origVal.Kind(); kind {
34
case reflect.Ptr:
35
val = origVal.Elem()
36
case reflect.Struct:
37
val = origVal
38
default:
39
panic(fmt.Errorf("expected Ptr or Struct, got %+v", kind))
40
}
41
for i := range val.NumField() {
42
iField := val.Field(i)
43
if isEmpty(iField) {
44
continue
45
}
46
iName := val.Type().Field(i).Name
47
if _, ok := knownNamesMap[iName]; !ok {
48
unknown = append(unknown, iName)
49
}
50
}
51
return unknown
52
}
53
54
func isEmpty(v reflect.Value) bool {
55
// NOTE: IsZero returns false for zero-length map and slice
56
if v.IsZero() {
57
return true
58
}
59
switch v.Kind() {
60
case reflect.Map, reflect.Slice:
61
return v.Len() == 0
62
}
63
return false
64
}
65
66