helper_test.go 1.4 KB

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