UnmarshalText implements the encoding.TextUnmarshaler interface.
(text []byte)
| 58 | |
| 59 | // UnmarshalText implements the encoding.TextUnmarshaler interface. |
| 60 | func (d *Duration) UnmarshalText(text []byte) error { |
| 61 | if text == nil { |
| 62 | *d = 0 |
| 63 | return nil |
| 64 | } |
| 65 | |
| 66 | var ( |
| 67 | out time.Duration |
| 68 | sign time.Duration = 1 |
| 69 | ) |
| 70 | match := durationRegexp.FindStringSubmatch(string(text)) |
| 71 | if match == nil || strings.Join(match[2:6], "") == "" { |
| 72 | return fmt.Errorf("invalid duration (%s)", text) |
| 73 | } |
| 74 | if match[1] == "-" { |
| 75 | sign = -1 |
| 76 | } |
| 77 | if match[2] != "" { |
| 78 | y, err := strconv.Atoi(match[2]) |
| 79 | if err != nil { |
| 80 | return fmt.Errorf("invalid duration years (%s): %s", text, err) |
| 81 | } |
| 82 | out += time.Duration(y) * year |
| 83 | } |
| 84 | if match[3] != "" { |
| 85 | m, err := strconv.Atoi(match[3]) |
| 86 | if err != nil { |
| 87 | return fmt.Errorf("invalid duration months (%s): %s", text, err) |
| 88 | } |
| 89 | out += time.Duration(m) * month |
| 90 | } |
| 91 | if match[4] != "" { |
| 92 | d, err := strconv.Atoi(match[4]) |
| 93 | if err != nil { |
| 94 | return fmt.Errorf("invalid duration days (%s): %s", text, err) |
| 95 | } |
| 96 | out += time.Duration(d) * day |
| 97 | } |
| 98 | if match[5] != "" { |
| 99 | match := durationTimeRegexp.FindStringSubmatch(match[5]) |
| 100 | if match == nil { |
| 101 | return fmt.Errorf("invalid duration (%s)", text) |
| 102 | } |
| 103 | if match[1] != "" { |
| 104 | h, err := strconv.Atoi(match[1]) |
| 105 | if err != nil { |
| 106 | return fmt.Errorf("invalid duration hours (%s): %s", text, err) |
| 107 | } |
| 108 | out += time.Duration(h) * time.Hour |
| 109 | } |
| 110 | if match[2] != "" { |
| 111 | m, err := strconv.Atoi(match[2]) |
| 112 | if err != nil { |
| 113 | return fmt.Errorf("invalid duration minutes (%s): %s", text, err) |
| 114 | } |
| 115 | out += time.Duration(m) * time.Minute |
| 116 | } |
| 117 | if match[3] != "" { |