sslobodr | d046be8 | 2019-01-16 10:02:22 -0500 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2014 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 conversion |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "reflect" |
| 22 | ) |
| 23 | |
| 24 | // EnforcePtr ensures that obj is a pointer of some sort. Returns a reflect.Value |
| 25 | // of the dereferenced pointer, ensuring that it is settable/addressable. |
| 26 | // Returns an error if this is not possible. |
| 27 | func EnforcePtr(obj interface{}) (reflect.Value, error) { |
| 28 | v := reflect.ValueOf(obj) |
| 29 | if v.Kind() != reflect.Ptr { |
| 30 | if v.Kind() == reflect.Invalid { |
| 31 | return reflect.Value{}, fmt.Errorf("expected pointer, but got invalid kind") |
| 32 | } |
| 33 | return reflect.Value{}, fmt.Errorf("expected pointer, but got %v type", v.Type()) |
| 34 | } |
| 35 | if v.IsNil() { |
| 36 | return reflect.Value{}, fmt.Errorf("expected pointer, but got nil") |
| 37 | } |
| 38 | return v.Elem(), nil |
| 39 | } |