time.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package time
  2. import (
  3. "context"
  4. "database/sql/driver"
  5. "strconv"
  6. xtime "time"
  7. )
  8. // Time be used to MySql timestamp converting.
  9. type Time int64
  10. // Scan scan time.
  11. func (jt *Time) Scan(src interface{}) (err error) {
  12. switch sc := src.(type) {
  13. case xtime.Time:
  14. *jt = Time(sc.Unix())
  15. case string:
  16. var i int64
  17. i, err = strconv.ParseInt(sc, 10, 64)
  18. *jt = Time(i)
  19. }
  20. return
  21. }
  22. // Value get time value.
  23. func (jt Time) Value() (driver.Value, error) {
  24. return xtime.Unix(int64(jt), 0), nil
  25. }
  26. // Time get time.
  27. func (jt Time) Time() xtime.Time {
  28. return xtime.Unix(int64(jt), 0)
  29. }
  30. // Duration be used toml unmarshal string time, like 1s, 500ms.
  31. type Duration xtime.Duration
  32. // UnmarshalText unmarshal text to duration.
  33. func (d *Duration) UnmarshalText(text []byte) error {
  34. tmp, err := xtime.ParseDuration(string(text))
  35. if err == nil {
  36. *d = Duration(tmp)
  37. }
  38. return err
  39. }
  40. // Shrink will decrease the duration by comparing with context's timeout duration
  41. // and return new timeout\context\CancelFunc.
  42. func (d Duration) Shrink(c context.Context) (Duration, context.Context, context.CancelFunc) {
  43. if deadline, ok := c.Deadline(); ok {
  44. if ctimeout := xtime.Until(deadline); ctimeout < xtime.Duration(d) {
  45. // deliver small timeout
  46. return Duration(ctimeout), c, func() {}
  47. }
  48. }
  49. ctx, cancel := context.WithTimeout(c, xtime.Duration(d))
  50. return d, ctx, cancel
  51. }