long.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package utils
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. type Long int64
  9. func (t Long) MarshalJSON() ([]byte, error) {
  10. b := fmt.Sprintf(`"%d"`, t)
  11. return []byte(b), nil
  12. }
  13. func (t *Long) UnmarshalJSON(value []byte) error {
  14. var v = strings.TrimSpace(strings.Trim(string(value), "\""))
  15. if v == "" {
  16. *t = Long(0)
  17. return nil
  18. }
  19. num, err := strconv.ParseInt(v, 10, 64)
  20. if err != nil {
  21. return err
  22. }
  23. *t = Long(num)
  24. return nil
  25. }
  26. func (t Long) MarshalText() ([]byte, error) {
  27. return []byte(t.String()), nil
  28. }
  29. func (t *Long) UnmarshalText(data []byte) error {
  30. *t = t.FromString(string(data))
  31. return nil
  32. }
  33. func (t Long) FromString(str string) Long {
  34. return ParseLong(str)
  35. }
  36. func ParseLong(str string) Long {
  37. str = strings.TrimSpace(str)
  38. num, err := strconv.ParseInt(str, 10, 64)
  39. if nil != err {
  40. return 0
  41. }
  42. return Long(num)
  43. }
  44. func (t Long) String() string {
  45. return strconv.FormatInt(int64(t), 10)
  46. }
  47. func (t Long) Value() (driver.Value, error) {
  48. if t.IsZero() {
  49. return int64(0), nil
  50. }
  51. return int64(t), nil
  52. }
  53. func (t *Long) Scan(value interface{}) error {
  54. if value == nil {
  55. return nil
  56. }
  57. if v, ok := value.(int64); ok {
  58. *t = Long(v)
  59. } else if v, ok := value.([]uint8); ok {
  60. num, err := strconv.ParseInt(string(v), 10, 64)
  61. if err == nil {
  62. *t = Long(num)
  63. }
  64. }
  65. return nil
  66. }
  67. func (t Long) IsZero() bool {
  68. return t == 0
  69. }
  70. // sort
  71. type ByLong []Long
  72. func (a ByLong) Len() int { return len(a) }
  73. func (a ByLong) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  74. func (a ByLong) Less(i, j int) bool { return a[i] < a[j] }