null_uint8.go 1.6 KB

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