duration.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package strfmt
  15. import (
  16. "database/sql/driver"
  17. "errors"
  18. "fmt"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/globalsign/mgo/bson"
  24. "github.com/mailru/easyjson/jlexer"
  25. "github.com/mailru/easyjson/jwriter"
  26. )
  27. func init() {
  28. d := Duration(0)
  29. // register this format in the default registry
  30. Default.Add("duration", &d, IsDuration)
  31. }
  32. var (
  33. timeUnits = [][]string{
  34. {"ns", "nano"},
  35. {"us", "µs", "micro"},
  36. {"ms", "milli"},
  37. {"s", "sec"},
  38. {"m", "min"},
  39. {"h", "hr", "hour"},
  40. {"d", "day"},
  41. {"w", "wk", "week"},
  42. }
  43. timeMultiplier = map[string]time.Duration{
  44. "ns": time.Nanosecond,
  45. "us": time.Microsecond,
  46. "ms": time.Millisecond,
  47. "s": time.Second,
  48. "m": time.Minute,
  49. "h": time.Hour,
  50. "d": 24 * time.Hour,
  51. "w": 7 * 24 * time.Hour,
  52. }
  53. durationMatcher = regexp.MustCompile(`((\d+)\s*([A-Za-zµ]+))`)
  54. )
  55. // IsDuration returns true if the provided string is a valid duration
  56. func IsDuration(str string) bool {
  57. _, err := ParseDuration(str)
  58. return err == nil
  59. }
  60. // Duration represents a duration
  61. //
  62. // Duration stores a period of time as a nanosecond count, with the largest
  63. // repesentable duration being approximately 290 years.
  64. //
  65. // swagger:strfmt duration
  66. type Duration time.Duration
  67. // MarshalText turns this instance into text
  68. func (d Duration) MarshalText() ([]byte, error) {
  69. return []byte(time.Duration(d).String()), nil
  70. }
  71. // UnmarshalText hydrates this instance from text
  72. func (d *Duration) UnmarshalText(data []byte) error { // validation is performed later on
  73. dd, err := ParseDuration(string(data))
  74. if err != nil {
  75. return err
  76. }
  77. *d = Duration(dd)
  78. return nil
  79. }
  80. // ParseDuration parses a duration from a string, compatible with scala duration syntax
  81. func ParseDuration(cand string) (time.Duration, error) {
  82. if dur, err := time.ParseDuration(cand); err == nil {
  83. return dur, nil
  84. }
  85. var dur time.Duration
  86. ok := false
  87. for _, match := range durationMatcher.FindAllStringSubmatch(cand, -1) {
  88. factor, err := strconv.Atoi(match[2]) // converts string to int
  89. if err != nil {
  90. return 0, err
  91. }
  92. unit := strings.ToLower(strings.TrimSpace(match[3]))
  93. for _, variants := range timeUnits {
  94. last := len(variants) - 1
  95. multiplier := timeMultiplier[variants[0]]
  96. for i, variant := range variants {
  97. if (last == i && strings.HasPrefix(unit, variant)) || strings.EqualFold(variant, unit) {
  98. ok = true
  99. dur += (time.Duration(factor) * multiplier)
  100. }
  101. }
  102. }
  103. }
  104. if ok {
  105. return dur, nil
  106. }
  107. return 0, fmt.Errorf("Unable to parse %s as duration", cand)
  108. }
  109. // Scan reads a Duration value from database driver type.
  110. func (d *Duration) Scan(raw interface{}) error {
  111. switch v := raw.(type) {
  112. // TODO: case []byte: // ?
  113. case int64:
  114. *d = Duration(v)
  115. case float64:
  116. *d = Duration(int64(v))
  117. case nil:
  118. *d = Duration(0)
  119. default:
  120. return fmt.Errorf("cannot sql.Scan() strfmt.Duration from: %#v", v)
  121. }
  122. return nil
  123. }
  124. // Value converts Duration to a primitive value ready to be written to a database.
  125. func (d Duration) Value() (driver.Value, error) {
  126. return driver.Value(int64(d)), nil
  127. }
  128. // String converts this duration to a string
  129. func (d Duration) String() string {
  130. return time.Duration(d).String()
  131. }
  132. // MarshalJSON returns the Duration as JSON
  133. func (d Duration) MarshalJSON() ([]byte, error) {
  134. var w jwriter.Writer
  135. d.MarshalEasyJSON(&w)
  136. return w.BuildBytes()
  137. }
  138. // MarshalEasyJSON writes the Duration to a easyjson.Writer
  139. func (d Duration) MarshalEasyJSON(w *jwriter.Writer) {
  140. w.String(time.Duration(d).String())
  141. }
  142. // UnmarshalJSON sets the Duration from JSON
  143. func (d *Duration) UnmarshalJSON(data []byte) error {
  144. l := jlexer.Lexer{Data: data}
  145. d.UnmarshalEasyJSON(&l)
  146. return l.Error()
  147. }
  148. // UnmarshalEasyJSON sets the Duration from a easyjson.Lexer
  149. func (d *Duration) UnmarshalEasyJSON(in *jlexer.Lexer) {
  150. if data := in.String(); in.Ok() {
  151. tt, err := ParseDuration(data)
  152. if err != nil {
  153. in.AddError(err)
  154. return
  155. }
  156. *d = Duration(tt)
  157. }
  158. }
  159. // GetBSON returns the Duration a bson.M{} map.
  160. func (d *Duration) GetBSON() (interface{}, error) {
  161. return bson.M{"data": int64(*d)}, nil
  162. }
  163. // SetBSON sets the Duration from raw bson data
  164. func (d *Duration) SetBSON(raw bson.Raw) error {
  165. var m bson.M
  166. if err := raw.Unmarshal(&m); err != nil {
  167. return err
  168. }
  169. if data, ok := m["data"].(int64); ok {
  170. *d = Duration(data)
  171. return nil
  172. }
  173. return errors.New("couldn't unmarshal bson raw value as Duration")
  174. }