null_int16.go 1.6 KB

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