github.com/sacloud/libsacloud/v2@v2.32.3/pkg/util/empty.go (about)

     1  // Copyright 2016-2022 The Libsacloud Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"reflect"
    19  )
    20  
    21  // IsEmpty is copied from github.com/stretchr/testify/assert/assetions.go
    22  func IsEmpty(object interface{}) bool {
    23  	// get nil case out of the way
    24  	if object == nil {
    25  		return true
    26  	}
    27  
    28  	objValue := reflect.ValueOf(object)
    29  
    30  	switch objValue.Kind() {
    31  	// collection types are empty when they have no element
    32  	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
    33  		return objValue.Len() == 0
    34  	// pointers are empty if nil or if the value they point to is empty
    35  	case reflect.Ptr:
    36  		if objValue.IsNil() {
    37  			return true
    38  		}
    39  		deref := objValue.Elem().Interface()
    40  		return IsEmpty(deref)
    41  	// for all other types, compare against the zero value
    42  	default:
    43  		zero := reflect.Zero(objValue.Type())
    44  		return reflect.DeepEqual(object, zero.Interface())
    45  	}
    46  }