github.com/ugorji/go/codec@v1.2.13-0.20240307214044-07c54c229a5a/helper_test.go (about)

     1  // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
     2  // Use of this source code is governed by a MIT license found in the LICENSE file.
     3  
     4  package codec
     5  
     6  // All non-std package dependencies related to testing live in this file,
     7  // so porting to different environment is easy (just update functions).
     8  
     9  import (
    10  	"errors"
    11  	"reflect"
    12  )
    13  
    14  // --- these functions are used by both benchmarks and tests
    15  
    16  var errDeepEqualNotMatch = errors.New("Not Match")
    17  
    18  func deepEqual(v1, v2 interface{}) (err error) {
    19  	if !reflect.DeepEqual(v1, v2) {
    20  		err = errDeepEqualNotMatch
    21  	}
    22  	return
    23  }
    24  
    25  func approxDataSize(rv reflect.Value) (sum int) {
    26  	switch rk := rv.Kind(); rk {
    27  	case reflect.Invalid:
    28  	case reflect.Ptr, reflect.Interface:
    29  		sum += int(rv.Type().Size())
    30  		sum += approxDataSize(rv.Elem())
    31  	case reflect.Slice:
    32  		sum += int(rv.Type().Size())
    33  		for j := 0; j < rv.Len(); j++ {
    34  			sum += approxDataSize(rv.Index(j))
    35  		}
    36  	case reflect.String:
    37  		sum += int(rv.Type().Size())
    38  		sum += rv.Len()
    39  	case reflect.Map:
    40  		sum += int(rv.Type().Size())
    41  		for _, mk := range rv.MapKeys() {
    42  			sum += approxDataSize(mk)
    43  			sum += approxDataSize(rv.MapIndex(mk))
    44  		}
    45  	case reflect.Struct:
    46  		//struct size already includes the full data size.
    47  		//sum += int(rv.Type().Size())
    48  		for j := 0; j < rv.NumField(); j++ {
    49  			sum += approxDataSize(rv.Field(j))
    50  		}
    51  	default:
    52  		//pure value types
    53  		sum += int(rv.Type().Size())
    54  	}
    55  	return
    56  }