gitlab.com/evatix-go/core@v1.3.55/coredata/coredynamic/CastTo.go (about)

     1  package coredynamic
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"gitlab.com/evatix-go/core/constants"
     7  	"gitlab.com/evatix-go/core/errcore"
     8  	"gitlab.com/evatix-go/core/internal/reflectinternal"
     9  )
    10  
    11  func CastTo(
    12  	isOutputPointer bool,
    13  	input interface{},
    14  	acceptedTypes ...reflect.Type,
    15  ) CastedResult {
    16  	currentRfType := reflect.TypeOf(input)
    17  	rv := reflect.ValueOf(input)
    18  	kind := rv.Kind()
    19  	var sliceErr []string
    20  
    21  	isMatchingAcceptedType := IsAnyTypesOf(
    22  		currentRfType,
    23  		acceptedTypes...)
    24  
    25  	if !isMatchingAcceptedType {
    26  		// not matching
    27  		sliceErr = append(
    28  			sliceErr,
    29  			errcore.UnsupportedType.Combine(
    30  				"none matches, current type:"+currentRfType.String(),
    31  				TypeNamesStringUsingReflectType(true, acceptedTypes...)))
    32  	}
    33  
    34  	isNull := input == nil || reflectinternal.IsNullUsingReflectValue(
    35  		rv)
    36  	isOutNonPointer := !isOutputPointer
    37  	hasNonPointerIssue := isNull && isOutNonPointer
    38  
    39  	if hasNonPointerIssue {
    40  		// has issue
    41  		// cannot non pointer a nil pointer
    42  		// will panic
    43  		sliceErr = append(
    44  			sliceErr,
    45  			errcore.
    46  				InvalidNullPointerType.
    47  				SrcDestination(
    48  					"cannot output non pointer if pointer is null",
    49  					"Value", constants.NilAngelBracket,
    50  					"Type", currentRfType.String()))
    51  
    52  		// ending process
    53  		return CastedResult{
    54  			Casted:                 nil,
    55  			SourceReflectType:      currentRfType,
    56  			SourceKind:             kind,
    57  			Error:                  errcore.SliceToError(sliceErr),
    58  			IsNull:                 isNull,
    59  			IsMatchingAcceptedType: isMatchingAcceptedType,
    60  			IsPointer:              isOutNonPointer,
    61  			IsSourcePointer:        kind == reflect.Ptr,
    62  			IsValid:                rv.IsValid(),
    63  		}
    64  	}
    65  
    66  	val, _ := PointerOrNonPointerUsingReflectValue(
    67  		isOutputPointer,
    68  		rv)
    69  
    70  	return CastedResult{
    71  		Casted:                 val,
    72  		SourceReflectType:      currentRfType,
    73  		SourceKind:             kind,
    74  		Error:                  errcore.SliceToError(sliceErr),
    75  		IsNull:                 isNull,
    76  		IsMatchingAcceptedType: isMatchingAcceptedType,
    77  		IsPointer:              isOutNonPointer,
    78  		IsSourcePointer:        kind == reflect.Ptr,
    79  		IsValid:                rv.IsValid(),
    80  	}
    81  }