null_float32.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package xorm
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "reflect"
  7. "strconv"
  8. )
  9. type NullFloat32 struct {
  10. Float32 float32
  11. Valid bool
  12. }
  13. func (nf NullFloat32) Ptr() *float32 {
  14. if !nf.Valid {
  15. return nil
  16. }
  17. return &nf.Float32
  18. }
  19. func (nf NullFloat32) ValueOrZero() float32 {
  20. if !nf.Valid {
  21. return 0
  22. }
  23. return nf.Float32
  24. }
  25. func (nf NullFloat32) IsNil() bool {
  26. return !nf.Valid
  27. }
  28. func (nf *NullFloat32) UnmarshalJSON(data []byte) error {
  29. var err error
  30. var v interface{}
  31. if err = json.Unmarshal(data, &v); err != nil {
  32. return err
  33. }
  34. switch x := v.(type) {
  35. case float64:
  36. nf.Float32 = float32(x)
  37. case string:
  38. str := string(x)
  39. if len(str) == 0 {
  40. nf.Valid = false
  41. return nil
  42. }
  43. var f float64
  44. f, err = strconv.ParseFloat(str, 32)
  45. if err == nil {
  46. nf.Float32 = float32(f)
  47. }
  48. case map[string]interface{}:
  49. err = json.Unmarshal(data, &nf)
  50. case nil:
  51. nf.Valid = false
  52. return nil
  53. default:
  54. err = fmt.Errorf("json: cannot unmarshal %v into Go value of type xorm.NullFloat32", reflect.TypeOf(v).Name())
  55. }
  56. nf.Valid = err == nil
  57. return err
  58. }
  59. func (nf *NullFloat32) UnmarshalText(text []byte) error {
  60. str := string(text)
  61. if str == "" || str == "null" {
  62. nf.Valid = false
  63. return nil
  64. }
  65. var err error
  66. var f float64
  67. f, err = strconv.ParseFloat(string(text), 32)
  68. if err == nil {
  69. nf.Float32 = float32(f)
  70. }
  71. nf.Valid = err == nil
  72. return err
  73. }
  74. func (nf NullFloat32) MarshalJSON() ([]byte, error) {
  75. if !nf.Valid {
  76. return []byte("null"), nil
  77. }
  78. if math.IsInf(float64(nf.Float32), 0) || math.IsNaN(float64(nf.Float32)) {
  79. return nil, &json.UnsupportedValueError{
  80. Value: reflect.ValueOf(nf.Float32),
  81. Str: strconv.FormatFloat(float64(nf.Float32), 'g', -1, 32),
  82. }
  83. }
  84. return []byte(strconv.FormatFloat(float64(nf.Float32), 'f', -1, 32)), nil
  85. }
  86. func (nf NullFloat32) MarshalText() ([]byte, error) {
  87. if !nf.Valid {
  88. return []byte{}, nil
  89. }
  90. return []byte(strconv.FormatFloat(float64(nf.Float32), 'f', -1, 32)), nil
  91. }